We also want to quickly debug our scripts with minimal fuss and high-end results.
This can be done using a very handy tracing feature, build directly into the Bash command interpreter.
We’ll look into this in the second topic.
You may also want to keep an eye out for our upcoming article on the related shellcheck.
And finally we will explore how to run scripts as a background process.
Script Debugging
Debugging a script in Bash need not be hard!
How will this help with debugging?
The-oidiom in theifstatement stands forOR, i.e.
So why is the script running into the assert?
Let’s debug this now with the-xoption to Bash.
It can also be initiated by simply typingbash, or in this casebash -xinside our top shell.
Something is being compared with1, but thatsomethingis… empty (as indicated by the empty string'')!
We quickly realize theAAinstead ofAmistake, correct the mistake, and the script now works fine!
We then capture stdout by usingteeand this will save the output to the file specified, namelybash_-x_output.txt.
As an example, I tend to usebash -xabout once every fortnight to debug complex scripts.
We also terminate oursleep 1command with a customaryend-of-commandBash idiom, after which we will execute anechothat thesleep 1is complete/done.
Let’s next check out what happens at execution of this line.
Immediately, our background process/script (background.sh) is started, and this will run for about 2 seconds.
After this ourechois executed, showing us thesleep 1is complete.
A second later, ourbackground.shprocess rounds up it’s 2 second wait, and terminates.
It also highlights how many commands and utilities can be used in a combinatory way in Bash.
Importing Scripts Usingsource
Importing another script can be done easily using the Bashsourcecommand.
This script is then sourced from thetestsource.shscript by using the instructionsource mysource.sh.
In Summary
We had a look at script debugging by usingbash -xto display all executed commands.