Skip to content

Shell Scripting Tips

String manipulation

  • The % sign removes the substring placed after it from the original variable.
sh
EXAMPLE="qwerty/asdf"
OTHER=${EXAMPLE%sdf}
echo ${OTHER}
# Output
qwerty/a
EXAMPLE="qwerty/asdf"
OTHER=${EXAMPLE%sdf}
echo ${OTHER}
# Output
qwerty/a

Check if file exists

sh
FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exists."
fi

# or if doesn't exist
if [ ! -f "$FILE" ]; then
	echo "$FILE doesn't exist."
fi
FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exists."
fi

# or if doesn't exist
if [ ! -f "$FILE" ]; then
	echo "$FILE doesn't exist."
fi

Check if variable is equal to a string

sh
if [ "${VARIBALE}" == "yourstring" ]; then
    # do something
elif [ "${VARIABLE}" == "anotherstring" ]; then
    # do something else
else
	# do something by default
fi
if [ "${VARIBALE}" == "yourstring" ]; then
    # do something
elif [ "${VARIABLE}" == "anotherstring" ]; then
    # do something else
else
	# do something by default
fi

Check if an input argument exists

sh
if [ -z "$1" ]; then
  echo "Need to specify the AWS profile: ./eb-init bradenstefanuk-profile"
  exit 1
fi
if [ -z "$1" ]; then
  echo "Need to specify the AWS profile: ./eb-init bradenstefanuk-profile"
  exit 1
fi

What is 2>&1

This command 2>&1 redirects stderr to stdout, that is, only errors are printed to the console. The stackoverflow solution describes it nicely: https://stackoverflow.com/questions/818255/what-does-21-mean

File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

At first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1".

& indicates that what follows and precedes is a file descriptor, and not a filename. Thus, we use 2>&1. Consider >& to be a redirect merger operator.

Default Variables

The following code will set the first command line argument to defaulted_ip, if no argument is provided then it will default to 192.168.168.100.

sh
defaulted_ip="${1:-192.168.168.100}"
defaulted_ip="${1:-192.168.168.100}"