WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.
There are some times when you cannot use Perl, Python or even Bash because you need to run scripts on legacy systems or systems you can't know for sure what shell they are using.
The POSIX shell (usually invokable via
/bin/sh) is a basic shell and a set of standards that you can use to make sure your scripts run no matter what shell you have.
POSIX-compliant scripts are supported by all major shell versions such as bash, tcsh, zsh, csh, etc. So if it works in sh it will also work in other shells.
If you need to make sure your scripts will run no matter what shell you have, POSIX-shell is the way to go. Avoid bashisms, i.e. code that works in bash but not on POSIX shells
Detecting that you are running sh
Run the following command:
ps -p $$
If you are indeed running sh, you'll see an output like the following:
PID TTY TIME CMD 10552 ? 00:00:00 sh
sh under CMD means you're running POSIX shell (likely
Simple if then else
if [ -f myfile.txt ]; then cat myfile.txt elif [ -f otherfile.txt ]; then cat otherfile.txt elif [ "foo" = "bar" ]; then echo "this will never be run!" else echo "files not found!" fi
Testing a string matches a regexp
A popular way is to use
SOME_VAR="foo-bar-3" if echo "$SOME_VAR" | grep -P '\d$';then echo "it ends in a digit!" else echo "it doesn't end in a digit!" fi
or, as a one-liner:
if [ 'a' != 'b' ]; then echo 'great success'; fi
Finding the return code of the last command run
# the following command will fail as it doesn't exist foo if [ "$?" != 0 ];then echo 'failed!' else echo 'all ok!' fi