Friday, July 27, 2012

How to debug a Bash shell script ?

When executing a shell script use 'bash' command with below options to debug a shell script in effective way. 
 -x if you set this option, it will show you each line before it executes it. Comments will not be reported.
sh -x scriptname.sh
-v Echo’s each line as it is read. It’s a kind of verbose and even echo back commented lines too.
sh -v scriptname.sh
Note: A small difference between –x and –v is that –v echo’s the line as it is read (So it will even display comments too.), whereas –x flag causes each command to be echoed as it is executed.
sh -xv scriptname.sh
-u –At times you use a variable without setting some value to it. If you use this flag it will give you the error saying so and so variable is not set before executing the script.
-e –Exit the shell script if any error occurs. This option will stop the script to run further once the script encounters an error. Use full for debugging the first error itself when running big scripts…
sh -e scriptname.sh

Saturday, July 14, 2012

Bash syntax to calculate sum list of numeric values in a file

Lets say you have a file which consists list of Numeric values and wish to add the total sum of all the numeric values. The bash syntax would be:
sum=0; for i in `cat filename.txt`; do sum=$(( $sum + $i )); done; echo $sum
(or)
declare -i sum=0; for i in `cat filename.txt`; do sum+=$i; done; echo $sum

Popular Posts

About Me

My photo
I have started this blog to share my work experience and spread some smart solutions on Linux to Internet community. I'm hoping more people will get benefited from this blog. Brief about me: I have 14+ years experience working as System Admin and currently work with VMware.