How to recognize whether bash or dash is being used within a script?
Asked Answered
A

5

9

I'm writing a bash script and it throws an error when using "sh" command in Ubuntu (it seems it's not compatible with dash, I'm learning on this subject). So I would like to detect if dash is being used instead of bash to throw an error.

How can I detect it in a script context?. Is it even possible?

Asthma answered 11/4, 2014 at 11:29 Comment(2)
What you can do is to define the interpreter in the first line of your script: #!/bin/bash will make it be executed with /bin/bash when called with ./script.sh. Also, good to see Pink Floyd around :)Costplus
bash's features are a superset of dash's features; dash is smaller and faster, but is mostly limited to POSIX features - see en.wikipedia.org/wiki/Debian_Almquist_shellCopyreader
C
15

You can check for the presence of shell-specific variables:

For instance, bash defines $BASH_VERSION. Since that variable won't be defined while running in dash, you can use it to make the distinction:

[ -n "$BASH_VERSION" ] && isBash=1

Afterthought: If you wanted to avoid relying on variables (which, conceivably, could be set incorrectly), you could try to obtain the ultimate name of the shell executable running your script, by determining the invoking executable and, if it is a symlink, following it to its (ultimate) target.

The shell function getTrueShellExeName() below does that; for instance, it would return 'dash' on Ubuntu for a script run with sh (whether explicitly or via shebang #!/bin/sh), because sh is symlinked to dash there.

Note that the function's goal is twofold:

  • Be portable:
    • Work with all POSIX-compatible (Bourne-like) shells,
    • across at least most platforms, with respect to what utilities and options are used - see caveats below.
  • Work in all invocation scenarios:
    • sourced (whether from a login shell or not)
    • executed stand-alone, via the shebang line
    • executed by being passed as a filename argument to a shell executable
    • executed by having its contents piped via stdin to a shell executable

Caveats:

  • On at least one platform - macOS - sh is NOT a symlink, even though it is effectively bash. There, the function would return 'sh' in a script run with sh.

  • The function uses readlink, which, while not mandated by POSIX, is present on most modern platforms - though with differing syntax and features. Therefore, using GNU readlink's -f option to find a symlink's ultimate target is not an option.
    (The only modern platform I'm personally aware of that does not have a readlink utility is HP-UX - see https://mcmap.net/q/109951/-relative-paths-based-on-file-location-instead-of-current-working-directory-duplicate for a recursive-readlink implementation that should work on all POSIX platforms.)

  • The function uses the which utility (except in zsh, where it's a builtin), which, while not mandated by POSIX, is present on most modern platforms.

  • Ideally, ps -p $$ -o comm= would be sufficient to determine the path of the executable underlying the process, but that doesn't work as intended when directly executing shell scripts with shebang lines on Linux, at least when using the ps implementation from the procps-ng package, as found on Ubuntu, for instance: there, such scripts report the script's file name rather than the underlying script engine's.Tip of the hat to ferdymercury for his help.
    Therefore, the content of special file /proc/$$/cmdline is parsed on Linux, whose first NUL-separated field contains the true executable path.

Example use of the function:

[ "$(getTrueShellExeName)" = 'bash' ] && isBash=1 

Shell function getTrueShellExeName():

getTrueShellExeName() {
  local trueExe nextTarget 2>/dev/null # ignore error in shells without `local`
  # Determine the shell executable filename.
  if [ -r /proc/$$/cmdline ]; then
    trueExe=$(cut -d '' -f1 /proc/$$/cmdline) || return 1
  else
    trueExe=$(ps -p $$ -o comm=) || return 1
  fi
  # Strip a leading "-", as added e.g. by macOS for login shells.
  [ "${trueExe#-}" = "$trueExe" ] || trueExe=${trueExe#-}
  # Determine full executable path.
  [ "${trueExe#/}" != "$trueExe" ] || trueExe=$([ -n "$ZSH_VERSION" ] && which -p "$trueExe" || which "$trueExe")
  # If the executable is a symlink, resolve it to its *ultimate*
  # target.
  while nextTarget=$(readlink "$trueExe"); do trueExe=$nextTarget; done
  # Output the executable name only.
  printf '%s\n' "$(basename "$trueExe")"
}
Copyreader answered 11/4, 2014 at 11:38 Comment(4)
You can use readlink -f to get the ultimate destination of a symlink, so in a sourced shell script (started with . ./script) one could use BIN="$(readlink -f $0)"; BIN="${BIN##*/}" to get the name of the shell without its path. In an executed script (started with ./script) one would have to extract the shebang, and follow that for symlinks...Triarchy
@zrajm: The purpose of my shell function is twofold: (a) be portable and (b) work in all invocation scenarios. I've updated my answer to clarify. Your suggestion doesn't satisfy (a), because readlink -f is a GNU extension that doesn't work on OSX, for instance. It doesn't satisfy (b), because analyzing the shebang line is insufficient - for instance, your script could have been passed as a direct argument to any shell executable instead.Copyreader
@zrajm: Furthermore, there is no simple, shell-neutral way that I know of to determine if a script is being sourced (do tell me if you know a way). Also, OSX, for instance, prepends - to the shell executable name reported in $0 in a login shell (on OSX, all shells created in a terminal are login shells), so you'd have to account for that (that's the easy part).Copyreader
Good idea, @ferdymercury - thanks; answer updated.Copyreader
D
6

Use $0 (that is the name of the executable of the shell being called).The command for example

echo $0

gives

/usr/bin/dash

for the dash and

/bin/bash

for a bash.The parameter substitution

${0##*/}

gives just 'dash' or 'bash'. This can be used in a test.

Decoct answered 11/4, 2014 at 14:55 Comment(2)
This isn't reliable. What if the script is executable and invoked as ./script? What if the script is sourced?Bullfight
$0 is set to an arbitrary string by whatever invokes the shell. It's almost always right...Stamper
B
2

An alternative approach might be to test if a shell feature is available, for example to give an idea...

[[ 1 ]] 2>/dev/null && echo could be bash || echo not bash, maybe dash
Belligerent answered 16/4, 2014 at 15:22 Comment(0)
A
-1
is_x_shell() { which ${1} >/dev/null && diff $(realpath /proc/$$/exe) $(which ${1}) >/dev/null; }

is_x_shell dash && echo is_dash
is_x_shell bash && echo is_bash
is_x_shell ash && echo is_ash
is_x_shell zsh && echo is_zsh
Anthropomorphosis answered 12/10, 2023 at 2:11 Comment(0)
I
-2
echo $0 and [[ 1 ]] 2>/dev/null && echo 

could be bash || echo not bash, maybe bash worked for me running Ubuntu 19.

Done slight Pascal, Fortran and C in school, but need to become fluent in shell script.

Immolate answered 30/11, 2019 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.