Shell scripting is a powerful way to automate processes and tasks in Linux. But it can be difficult to get a shell script working unless you enable debugging in it. By default, debugging is not enabled in shell script. All you see is error message if there is any error. In this article, we will look at how to enable debugging in shell script. You can do this in two ways – from within shell script or from command line during runtime. We will look at both these methods.
How to Debug Shell Script
Here are the two ways to debug shell script. Either you can add the line ‘set -xv’ inside the shell script, or you can use -xv option while running shell script.
Debug Shell Script from Code
Here is an example of script where we have enabled debugging within the script. Create a blank shell script
$ sudo vi debug_script.sh
Add the following lines in it.
#!/bin/bash set -xv # This will enable debug cd /home/data/ for i in "*.txt"; do du -sh $i done
Save and close the file.
Make the shell script executable and run it.
$ sudo chmod +x debug_script.sh ./debug_script.sh
You will see the following kind of output.
cd /home/ubuntu/ + cd /home/ubuntu/ for i in "*.txt"; do du -sh $i done + for i in '"*.txt"' + du -sh boot.txt mysqld.txt post111.txt post1121.txt yum.txt 0 boot.txt 32K mysqld.txt 0 post111.txt 0 post1121.txt 4.0K yum.txt
As you can see the shell displays the executed lines along with their output, and any error messages, making it easy to debug your shell script.
Debug Script from Command Line
You can also debug script from command line by simply adding -xv option while running the script, as shown. Create a shell script.
$ sudo vi debug_script.sh
Add the following lines to it.
#!/bin/bash cd /home/data/ for i in "*.txt"; do du -sh $i done
In this code, we have not included ‘set -xv’ command. Execute the above script with the following command.
$ bash -xv ./debug_script.sh
You will see the following kind of output.
cd /home/ubuntu/ + cd /home/ubuntu/ for i in "*.txt"; do du -sh $i done + for i in '"*.txt"' + du -sh boot.txt mysqld.txt post111.txt post1121.txt yum.txt 0 boot.txt 32K mysqld.txt 0 post111.txt 0 post1121.txt 4.0K yum.txt
In this article, we have looked at two ways to debug shell script – from code and from command line. You can use either mode to debug your shell scripts easily.
Also read:
How to Sort Text File in Python
How to Check UFW Log & Status
How to Create Symbolic Links in Linux
Ubuntu Change Terminal Font Size & Color
How to Remove Sticky Bit in Linux
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.