1824623 Members
4268 Online
109672 Solutions
New Discussion юеВ

Shell script debugging

 
Paul Remeika
Occasional Contributor

Shell script debugging

How can I debug a shell script that I have written?
5 REPLIES 5
Alex Lavrov.
Honored Contributor

Re: Shell script debugging

You can execute it with:
sh -x my_script.sh

or change the first line of the script, from:
#!/bin/sh
to
#!/bin/sh -x


If you use sh/bash ofcourse.
I don't give a damn for a man that can only spell a word one way. (M. Twain)
Victor Fridyev
Honored Contributor

Re: Shell script debugging

Hi

You can run it either as
sh -x script
or
insert set -x into the script on the place, which you want to debug


HTH
Entities are not to be multiplied beyond necessity - RTFM
Bill Hassell
Honored Contributor

Re: Shell script debugging

A couple of notes about set -x:

It will show each step of your script that was executed (with a + in front of each command) but not exactly line by line. A line that has several commands piped into each other will show each command separately. The if or test statements will be shown but the lines that were not executed won't be shown.

To help with the above scenario, use -x and -v. The -v option shows each line (including comments). Note that because the shell is interpreting the script, the original statements and the trace lines may not always be interleaved together. But it does help see where the script is located during the test run.

Another feature of set -x is that the output goes to stderr. Normally, stdout and stderr go to the screen together, but suppose you want to step through the script one page at a time:

sh -vx myscript | more

What you'll see is all the lines for listing and debugging (immediately) and any of the stdout from the script will go to: | more. To put the two together so that the more command controls all output:

sh -x -v myscript 2>&1 | more

The 2> refers to redirecting stderr and the &1 refers to file descriptor 1 which is stdout. 2>&1 effectively ties both types of output together, so now the more command sees both streams of text.


Bill Hassell, sysadmin
Muthukumar_5
Honored Contributor

Re: Shell script debugging

You can also use set -x and set +x to debug shell script.

#!/bin/ksh
#debug
hostname
# debug starts
set -x
ls
echo bye
set +x
echo over
exit 0

HTH.
Easy to suggest when don't know about the problem!
f. halili
Trusted Contributor

Re: Shell script debugging

# ksh -x script.ksh
or
# sh -x script.sh


- f. halili
derekh