How can we debug a UNIX shell script?

By default, shell scripts like bash, sh, ksh etc read the script or command written in script file as it is and execute them entirely starting from identifying the relevant shell command interpreter to end but in case if there is issue in wrong scripting or that particular command or even condition does not meet the requirement it gets fail therefore we need something through which we can debug our script or get to know the reason why script is getting fail.
Fortunately, most of the shells like bash or sh provides shell script debug command through which you can identify why your shell script is getting fail. For debugging the
Bash shebang (shell command interpreter) based script you can use bash -x and for debugging sh shebang based script you can use sh -x

In below example I have written simple bash script hello.sh

  1. charanjit.singh:~$ cat hello.sh 
  2. #!/bin/bash  
  3. read -p "What is your Name: " name 
  4. echo -e "=================================================
  5. ==============\n" 
  6. echo -e "\n Hello $name Welcome to Linux World!" 
  7. echo -e "\n**********************************************
  8. ***************" 
  9. charanjit.singh:~$ 

This Bash shell script is running fine in normal execution by executing it as $./hello.sh

Now if I want to debug what script line or variable is being passed during execution I have used bash -x command: $bash -x hello.sh

Likewise, you can see I am getting detail shell script execution steps output and also able to identify what script line or variable is doing which function during execution.

Next Post
No Comment
Add Comment
comment url