top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are ways to debug a shell script problem, examples would be helpful?

+1 vote
435 views
What are ways to debug a shell script problem, examples would be helpful?
posted Feb 27, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Although this is somewhat dependent on what the problem is, there are a few commonly used methods for debugging shell script problems.

One method, which is frequently used across all programming languages, is to insert some debug statements within the shell script to output information to help pinpoint where and why the problem is being introduced.

Another method specific to shell scripting is using "set -x" to enable debugging.

Details:

Consider the following shell script example (notice that "set -x" is commented out at this time):

#!/bin/ksh
#set -x
i=1
while [ $i -lt 6 ]
do
print "in loop iteration: $i"
((i+=1))
done
exit

This script will produce the following output:

$ ./script1
in loop iteration: 1
in loop iteration: 2
in loop iteration: 3
in loop iteration: 4
in loop iteration: 5
$

If we uncomment (remove the #) from the "set -x" line in the script, this is what is displayed when the script runs:

$ ./script1
+ i=1
+ [ 1 -lt 6 ]
+ print in loop iteration: 1
in loop iteration: 1
+ let i+=1
+ [ 2 -lt 6 ]
+ print in loop iteration: 2
in loop iteration: 2
+ let i+=1
+ [ 3 -lt 6 ]
+ print in loop iteration: 3
in loop iteration: 3
+ let i+=1
+ [ 4 -lt 6 ]
+ print in loop iteration: 4
in loop iteration: 4
+ let i+=1
+ [ 5 -lt 6 ]
+ print in loop iteration: 5
in loop iteration: 5
+ let i+=1
+ [ 6 -lt 6 ]
+ exit
$

In addition to displaying the intended output ("in loop iteration" lines), enabling debugging with "set -x" also shows each line of execution preceded by a plus sign (+).

Although this can become unwieldly for larger shell scripts, it should be obvious how useful this can be when debugging a shell script to identify the root cause of a problem.

answer Feb 29, 2016 by Manikandan J
Similar Questions
0 votes

I have noticed that in shell script comments are also useful to perform some task,
for ex:
if i write #!/bin/bash/
or if i write #!/bin/sh/

in both the example script behavior is different,
both are comments then why it is giving different behavior?

+2 votes

I am using below script to validate IPV6 address but this script also pass invalid IP such as empty string, name etc.

if [[ "$IPv6ADDR"=~"^:?([a-fA-F0-9]{1,4}(:|.)?){0,8}(:|::)?([a-fA-F0-9]{1,4}(:|.)?){0,8}$" ]]; then
  echo "valid ipv6 addr"
  break;
else
  echo "Invalid IP Address"
  break;
fi

Can someone identify what's wrong in the regex, Please?

0 votes

I have a shell script copyScript.sh present in my pendrive.
What i want is, Whenever i connect pendrive to my pc this script should be run automatically.

Is it possible?
If yes then how to achieve this?

...