As a (Debian) Linux newbie I was wondering if there is a way to track the execution of a bash shell (.sh) script ? Like in Windows you trigger that with a echo on command in a batch file.
My first 'unix' script ever, but I'm wondering if it will run as expected :
#!/bin/bash
# switch maintenance mode off and go live with your ownCloud
occpath='/var/www/owncloud'
htuser='www-data'
alias occ-do=sudo -u $htuser php $occpath/occ
echo info: Switching to live-mode ..
occ-do maintenance:mode --on` the line I'm trying to create is like sudo -u www-data php /var/www/owncloud/occ (occ is what should be executed, let's assume I don't need a path for the php part).
Will this work; any mistakes in the syntax? And let's not forget my question about the execution following ..
23 Answers
Is there is a way to track the execution of a bash shell (.sh) script?
You can use set -x, set +x and set -v as described below.
set -x: Display commands and their arguments as they are executed.set +x: Turn off debuggingset -v: Display shell input lines as they are read.
HowTo: Debug a Shell Script Under Linux or UNIX
1. Use
-xoption to debug a shell scriptRun a shell script with -x option.
$ bash -x script-name $ bash -x domains.sh2. Use of
setbuiltin commandBash shell offers debugging options which can be turn on or off using set command.
- set -x : Display commands and their arguments as they are executed.
- set -v : Display shell input lines as they are read.
You can use above two commands in shell script itself:
#!/bin/bash clear # turn on debug mode set -x for f in * do file $f done # turn OFF debug mode set +x ls # more commandsYou can replace the standard Shebang line:
#!/bin/bashwith the following (for debugging) code:
#!/bin/bash -xv
Source HowTo: Debug a Shell Script Under Linux or UNIX
Further Reading
- An A-Z Index of the Bash command line for Linux - An excellent reference for all things Bash command line related.
- set - Manipulate shell variables and functions.
Put
set -xat the point where you want debug info start to showand
set +xwhere you want it off. I don't promise what you see will always be straightforward but you can get used to id after a while.
This is the simple way to check the syntax of your shell scripts :
Here in this website, the online syntax checker marks the line & displays the error which is caused due to incorrect syntax
As per the suggestion from other answers, you can try set -x & set +x to enable & disable debug mode respectively for tracking the execution of script.