Showing posts with label shell script. Show all posts
Showing posts with label shell script. Show all posts

Sunday, January 20, 2008

Debugging shell scripts

Sometimes you might need to debug or see what is really running in your shell script. If you want to see each line/command executed simply add "-x" to your first line where you define your shell/interpreter. This will output every executed command with a "+" before the line.

#! /bin/sh -x
echo "Hello World!"

This will output :

+echo "Hello World!"
Hello World!

I know this works with sh and bash, but I do not know the other shells.

Also debugging especially long shell scripts can be a hard job. If you set the "-x" option at the beginning of the script, then it will output all the commands executed.
For this purpose, you can add "set -x" before the place you want to debug and "set +x" at the end.

#! /bin/sh
echo "This is the test"
set -x
echo "Only show this part"
set +x

This will output:

This is the test
+echo "Only show this part"
+set +x
Only show this part


Also if you want to run your script, but not execute the commands you can use the -n option. This is best for checking your syntax.
Happy debugging with your favorite shell.