Hack 86. How to Debug a shell script

To debug a shell script use set –xv inside the shell script at the top.

Shell script with no debug command:

$ cat filesize.sh
#!/bin/bash
for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
do
  let totalsize=$totalsize+$filesize
done
echo "Total file size in current directory: $totalsize"

Output of Shell script with no debug command:

$ ./filesize.sh
Total file size in current directory: 652

Shell script with Debug command inside:

Add set –xv inside the shell script now to debug the output as shown below.

$ cat filesize.sh
#!/bin/bash
set -xv
for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
do
  let totalsize=$totalsize+$filesize
done
echo "Total file size in current directory: $totalsize"

Output of Shell script with Debug command inside:

$ ./fs.sh
++ ls -l .
++ grep '^-'
++ awk '{print $5}'
+ for filesize in '$(ls -l . | grep "^-" | awk '\''{print $5}'\'')'
+ let totalsize=+178
+ for filesize in '$(ls -l . | grep "^-" | awk '\''{print $5}'\'')'
+ let totalsize=178+285
+ for filesize in '$(ls -l . | grep "^-" | awk '\''{print $5}'\'')'
+ let totalsize=463+189
+ echo 'Total file size in current directory: 652'
Total file size in current directory: 652

Execute Shell script with debug option:

Instead of giving the set –xv inside the shell script, you can also provide that while executing the shell script as shown below.

$ bash -xv filesize.sh

Comments on this entry are closed.

  • MARIMUTHU November 1, 2010, 1:35 am

    Dear Sir / Madam,
    Its realy very helpful to me to know the advanced LINUX Command and scripts. from our web site…
    Thanks
    Prof. Mr. MARIMUKTU
    Dept. Of Computer Science,
    ASC College CHOPDA.

  • Santhosh January 2, 2011, 5:00 pm

    I found all the things were exiting. Especially this debugging was super.

    It is useful in many situations and helped me a lot.

  • valentino May 27, 2011, 5:14 pm

    i really love to be an hacker to and i love to know more about this linux

  • sahil goenka November 2, 2012, 9:54 am

    Thanks,

    These are really beneficial for me…but i have some doubts .. and how can i suscribe this.

  • R viswanath reddy April 25, 2013, 6:28 pm

    #!/bin/bash -xv

    echo “Hello world”

    would do the same thing.