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/aEXAMPLE="qwerty/asdf"
OTHER=${EXAMPLE%sdf}
echo ${OTHER}
# Output
qwerty/aCheck 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."
fiFILE=/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."
fiCheck 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
fiif [ "${VARIBALE}" == "yourstring" ]; then
# do something
elif [ "${VARIABLE}" == "anotherstring" ]; then
# do something else
else
# do something by default
fiCheck if an input argument exists
sh
if [ -z "$1" ]; then
echo "Need to specify the AWS profile: ./eb-init bradenstefanuk-profile"
exit 1
fiif [ -z "$1" ]; then
echo "Need to specify the AWS profile: ./eb-init bradenstefanuk-profile"
exit 1
fiWhat 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>1may look like a good way to redirectstderrtostdout. However, it will actually be interpreted as "redirectstderrto a file named1".
&indicates that what follows and precedes is a file descriptor, and not a filename. Thus, we use2>&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}"