Posted in bash

Watching a bash Script at Work

Sometimes it is helpful to watch what a bash script is actual doing. This can be done with the parameter -x:

$ bash -x <script>

Let’s look at this little script, called testscript:

#!/usr/bin/env bash
cd ~
date
ls -al > home.txt
ls -al /tmp/does_not_exist
date

Now let’s see the script working:

$ bash -x ./testscsript
+ cd /home/lemath
+ date
Sun Jan 29 10:42:35 CET 2017
+ ls -al
+ ls -al /tmp/does_not_exist
ls: /tmp/does_not_exist: No such file or directory
+ date
Sun Jan 29 10:42:35 CET 2017

We can see:

  • every command is prefixed with +,
  • stderr and stdout are shown as usual,
  • redirections are not shown.

But there is more! The prefix + is stored in the environment variable PS4:

$ echo $PS4
+

You can use other environment variables in the prompt, e.g.

  • \t prints the actual timestamp (for a sort of profiling),
  • $BASH_SOURCE: the name of the actual file (useful, if you call other scripts),
  • $LINENO: the line number in the script.

Set the new prompt:

$ export PS4='[-- \t $BASH_SOURCE:$LINENO --] '

You have to use single quotes, so that the variables are not expanded immediately.
Let’s see, what changed:

$ bash -x ./testscript
[-- 10:55:42 ./testscript:2 --] cd /home/lemath
[-- 10:55:42 ./testscript:3 --] date
Sun Jan 29 10:55:42 CET 2017
[-- 10:55:42 ./testscript:4 --] ls -al
[-- 10:55:42 ./testscript:5 --] ls -al /tmp/does_not_exist
ls: /tmp/does_not_exist: No such file or directory
[-- 10:55:42 ./testscript:6 --] date
Sun Jan 29 10:55:42 CET 2017

Now you can follow the script line by line.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s