Shell Script

Format

Start them all with the shell execution environment you want. e.g

#!/bin/sh

I always try to have this pointing to sh and then point bin/sh to a POSIX compliant shell. Good standards guarantee the script will work in as many places as possible!

Exiting

Exiting a scipt is done using the exit keyword, to exit a script indicating success to the script, exit with a value of zero otherwise exit with any other value to indicate an error:

Success:

exit 0

Error:

exit 1

Output

Output from scripts is usually done with echo, although anything you execute will, by default, have it’s output visible too through stdout and stderr

echo "Hello"

Will direct Hello to stdout

echo "Hello" 1>&2

Will direct Hello stderr

Functions

It’s possible to write and use functions in a bash script which generally makes then much more readable

function Error {
echo $1 1>&2
}

Quick Snippets

Test user is root

if [[ $EUID -ne 0 ]]; then
  echo "You must be a root user" 1>&2
  exit 1
else
  ...
fi

Logic / Conditionals

Test if a file exists:

if [ -e "/some/path/to/file.txt" ]; then
    something
    ...
else
    something
    ...
fi

You can use the not operator:

if [ ! -e "/some/path/to/file.txt" ]; then
    something
    ...
fi

To print stuff, use echo

echo "Something for the script executioner to see"

SCP Commands

Copy the file “foobar.txt” from a remote host to the local host

scp your_username@remotehost.local:foobar.txt /some/local/directory

Copy the file “foobar.txt” from the local host to a remote host

$ scp foobar.txt your_username@remotehost.local:/some/remote/directory

Parameter Expansion

See further information here: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02

Some useful examples:

${parameter%word}

    x=file.c
    echo ${x%.c}.o
    file.o

${parameter%%word}

    x=posix/src/std
    echo ${x%%/*}
    posix

${parameter#word}

    x=$HOME/src/cmd
    echo ${x#$HOME}
    /src/cmd

Leave a Reply