1

I have to run a number of shell scripts that are defined by a third party. So I cannot (or would prefer not to) change their content or which shell (bash vs. dash) they are using. They may or may not specify that via a shebang.

However, I want to print all executed commands to stdout. For bash, I can do that by using env SHELLOPTS=xtrace ./script.sh. However, this only works as long as the shebang #!/bin/bash is used. If #!/bin/dash or no shebang is used, this has no effect.

Is there an equivalent environment variable for dash that I can use? I know I could add set -x to the top of the script and that would work for both shells, but I would like to avoid that if possible.

1 Answer 1

4

There is no general replacement.

For the particular case of xtrace at just the top level script, you can use

dash -x ./script.sh

if you don't want to edit your script. The other thing you could do is create a wrapper script, something like

#!/bin/dash
set -x
. ./script.sh

In the comments you said you didn't want to tie things to dash. You could write a program, e.g. this called xtrace

#!/bin/bash
where=$(command -v "$1")
read line1 < "$where"
case "$line1" in
    (*"dash")
          # Assume if it mention dash on first line then it is a dash script
          exec /bin/dash -x "$@" ;;
    (*)
          SHELLOPTS=xtrace exec "$@" ;;
esac

and then use xtrace ./script.shto run it.

2
  • Thanks! But this enforces the usage of dash, right? I'm not really sure, but if there's some significant difference between dash and bash, I would like to execute each script with the shell it was designed for. And I need to do so without inspecting each script to pick the correct wrapper. Commented Feb 11, 2022 at 22:13
  • 1
    If you go the wrapper approach you need a wrapper per script anyhow, so you can select bash or dash at the time you create the script. In general bash provides a superset of POSIX requirements and dash is smaller, faster and closer to POSIX. Executing everything with bash will probably work unless someone has deliberately attempted to tell if bash or dash is being used.
    – icarus
    Commented Feb 11, 2022 at 22:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .