Previous post:

Next post:

Hack 86. How to Debug a shell script

by Ramesh

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
Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Previous post:

Next post:

{ 3 comments… read them below or add one }

1 MARIMUTHU November 1, 2010 at 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.

2 Santhosh January 2, 2011 at 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.

3 valentino May 27, 2011 at 5:14 pm

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

Leave a Comment

Previous post:

Next post: