First line of a script

so we all know the first line of a shell script has to have the shell defined as in:

#!/bin/bash

so, how do i have this automatically changed in a script so a certain shell is used, given the OS the script is running on?

i tried making this the very first few lines in the script:

UNAMEA=$(uname)
if [ "${UNAMEA}" = "SunOS" ] ; then
        echo "#!/usr/xpg4/bin/bash"
else
        echo "#!/bin/bash"
fi

which kicks out errors such as this:

script.sh: line 4: syntax error near unexpected token `else'
script.sh: line 4: `else'

any ideas on how to accomplish what i'm trying to do?

You can't put variables in the shebang. You could use the following depending on if you have the right bash path in your $PATH variable:

#!/usr/bin/env bash
1 Like

Someone should also point out that people write scripts for a particular shell. If I write a script for ksh, I can't be certain that it will run as is in bash. At least not without testing first.

You can create a sym link such as /usr/local/bin/bash that points to /bin/bash. Then use /usr/local/bin/bash as your shebang. This could give you the option of pointing it to /bin/zsh if you want. But making that kind of change could still break some or all of your scripts.

1 Like

Or instead of

/path/to/yourscript

run your script like this:

env PATH=/usr/xpg4/bin:/usr/bin bash /path/to/yourscript

The shebang is ignored then.

1 Like

this looks like what i'm looking for. is there anyway i can have that run in the script automatically? the goal here is to have the user run just one script without having to type anything extra.

i tried this:

#!$(env PATH=/usr/xpg4/bin:/usr/bin:/bin sh)