Using the set command

Most of the time, we invoke the debugging mode from the first line of script. This debugging mode will remain active until the last line of code. But many times, we may need to enable debugging for a particular section of script. By using the set command, we can enable and disable debugging at any point in our shell script:

    set -x
    section of script
    set +x
  

Consider the following script:

#!/bin/bash 
 
str1="USA" 
str2="Canada"; 
 
[ $str1 = $str2 ] 
echo $? 
 
Set -x 
 
[ $str1 != $str2 ] 
echo $? 
 
[ -z $str1 ] 
echo $? 
 
Set +x 
 
[ -n $str2 ] 
echo $? 
 
Exit 0 

In this case, the debugging will be enabled after the set -x and will be disabled immediately after the set +x.

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.