In most of the programming languages debugger tool is available for debugging. A debugger is a tool that can run a program or script that enables you to examine the internals of the script or program as it runs. In the shell scripting we don”t have any debugger tool but with the help of command line options (-n, -v and -x ) we can do the debugging.
Disabling the Shell ( -n option)
The -n option, shot for noexec ( as in no execution), tells the shell to not run the commands. Instead, the shell just checks for syntax errors. This option will not convince the shell to perform any more checks. Instead the shell just performs the normal syntax check. With -n option, the shell doesn’t execute your commands, so you have a safe way to test your scripts if they contain syntax error.
The follow example shows how to use -n option.
Let us consider a shell script with a name debug_quotes.sh
Now run the script with -n option
As the above outputs shows that there is syntax error , double quotes are missing.
Displaying the Scripts Commands ( -v option )
The -v option tells the shell to run in verbose mode. In practice , this means that shell will echo each command prior to execute the command. This is very useful in that it can often help to find the errors.
Let us create a shell script with the name “listusers.sh” with below contents
Now execute the script with -v option.
In the above output , script output gets mixed with commands of the scripts. But however , with -v option , at least you get a better view of what the shell is doing as it runs your script.
Combining the -n & -v Options
We can combine the command line options ( -n & -v ). This makes a good combination because we can check the syntax of a script while seeing the script output.
Let us consider a previously used script “debug_quotes.sh”
Tracing Script Execution ( -x option )
The -x option, short for xtrace or execution trace, tells the shell to echo each command after performing the substitution steps. Thus , we can see the values of variables and commands. Often, this option alone will help to diagnose a problem.
In most cases, the -x option provides the most useful information about a script, but it can lead to a lot of output. The following example show this option in action.
In the above output , shell inserted a + sign in front of the commands.
No comments:
Post a Comment