Posted By: Anonymous
Is there any way to debug a bash script? E.g something that prints a sort of execution log like “calling line 1”, “calling line 2” etc.
sh -x script [arg1 ...] bash -x script [arg1 ...]
These give you a trace of what is being executed. (See also ‘Clarification’ near the bottom of the answer.)
This turns debugging on. You can then turn it off again with:
(You can find out the current tracing state by analyzing
$-, the current flags, for
Also, shells generally provide options ‘
-n‘ for ‘no execution’ and ‘
-v‘ for ‘verbose’ mode; you can use these in combination to see whether the shell thinks it could execute your script — occasionally useful if you have an unbalanced quote somewhere.
There is contention that the ‘
-x‘ option in Bash is different from other shells (see the comments). The Bash Manual says:
Print a trace of simple commands,
selectcommands, and arithmetic
forcommands and their arguments or associated word lists after they are expanded and before they are executed. The value of the
PS4variable is expanded and the resultant value is printed before the command and its expanded arguments.
That much does not seem to indicate different behaviour at all. I don’t see any other relevant references to ‘
-x‘ in the manual. It does not describe differences in the startup sequence.
Clarification: On systems such as a typical Linux box, where ‘
/bin/sh‘ is a symlink to ‘
/bin/bash‘ (or wherever the Bash executable is found), the two command lines achieve the equivalent effect of running the script with execution trace on. On other systems (for example, Solaris, and some more modern variants of Linux),
/bin/sh is not Bash, and the two command lines would give (slightly) different results. Most notably, ‘
/bin/sh‘ would be confused by constructs in Bash that it does not recognize at all. (On Solaris,
/bin/sh is a Bourne shell; on modern Linux, it is sometimes Dash — a smaller, more strictly POSIX-only shell.) When invoked by name like this, the ‘shebang’ line (‘
'#!/bin/sh‘) at the start of the file has no effect on how the contents are interpreted.
The Bash manual has a section on Bash POSIX mode which, contrary to a long-standing but erroneous version of this answer (see also the comments below), does describe in extensive detail the difference between ‘Bash invoked as
sh‘ and ‘Bash invoked as
When debugging a (Bash) shell script, it will be sensible and sane — necessary even — to use the shell named in the shebang line with the
-x option. Otherwise, you may (will?) get different behaviour when debugging from when running the script.