POSIX Shell: Basic Examples and Common Operations

POSIX Shell: Basic Examples and Common Operations

Last updated:

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.

Posix-compliant code works on all shells

What shell am I running?

Run the following command: ps -p $$ Shell type Output of ps -p$$
bash
$ps -p $$PID TTY TIME CMD 16464 pts/1 00:00:00 bash posix shell (sh)  ps -p$$ PID TTY TIME CMD 15441 pts/1 00:00:00 sh The sh under CMD means you're running POSIX shell (likely /bin/sh) POSIX-shell shebang Include the following line at the beginning of any shell source file you want to be run with sh (i.e. the POSIX shell) #!/usr/bin/env sh  Any code in this file will be run with the posix-shell, so all code must be posix-compliant (i.e. no bashism). String matches regex To find out if a string matches a regular expression. a popular way is to use echo and grep together. Example: string ends in a digit #!/usr/bin/env sh 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  Get return code of last command #!/usr/bin/env sh # the following command will fail as it doesn't exist foo if [ "$?" != 0 ];then
echo 'failed!'
else
echo 'all ok!'
fi