POSIX Shell: Basic Examples and Common Operations

Last updated:

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:

10552 ?        00:00:00 sh

The sh under CMD means you're running POSIX shell (likely /bin/sh)

Twitter Linkedin YC Hacker News Reddit

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!"
  echo "files not found!" 

Testing a string matches a regexp

A popular way is to use echo and grep together:


if echo "$SOME_VAR" | grep -P '\d$';then
  echo "it ends in a digit!"
  echo "it doesn't end in a digit!"

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

if [ "$?" != 0 ];then
  echo 'failed!'
  echo 'all ok!'

More info

Dialogue & Discussion