Bash Shell Cheatsheet
NOTE: The content in this page is my personal note which I got from multiple sources and based on my personal experience.
File Redirection
> file Create file
>> file Append to file
< file Read from file
a | b Pipe a as input to b
Read text file line by line
while read f; do
echo "line is $f"
done < file
While loop
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
For loop
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
for FILE in $HOME/.bash*
do
echo $FILE
done
Until loop
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Select loop
The select loop provides an easy way to create a numbered menu from which users can select options. It is useful when you need to ask the user to choose one or more items from a list of choices.
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN.
For every selection a set of commands would be executed with-in the loop. This loop was introduced in ksh and has been adapted into bash. It is not available in sh.
Here is a simple example to let the user select a drink of choice
#!/bin/ksh
select DRINK in tea cofee water juice appe all none
do
case $DRINK in
tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
The menu presented by the select loop looks like the following
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
You can change the prompt displayed by the select loop by altering the variable PS3 as follows −
$PS3="Please make a selection => " ; export PS3
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$
Get output of ls into variable
myvar=`ls`
Function declaration
doubleit(){
expr $1 \* 2
}
doubleit 3 # return 6
Run cmd1; if fails, run cmd2
cmd1 || cmd2
Run cmd1; if it works, run cmd2
cmd1 && cmd2
Test operators
if [ "$x" -lt "$y" ]; then
# do something
fi
Numeric tests
lt less than
gt
eq
ne
ge
le
File tests
nt newer than
d is a directory
f is a file
x executable
r redable
w writable
String tests
= equal to
z zero length
n not zero length
Logical test
&&
||
!
Arguments
$0
$1
...
$# no of arguments
$* all arguments
Variable substitution
${V:-default} $V, or "default if unset
${V:=default} $V (set to "default" if unset)
${V:?err} $, or "err" if unset
Preset Varibales
$SHELL What shell is running
$RANDOM Provides random number
$SECONDS Number of seconds from the time the shell is started
$$ PID of current process
$? Return code from last command
$! PID of last background cmd
$USER The username of the user running the script.
$HOSTNAME The hostname of the machine the script is running on.
$LINENO Returns the current line number in the Bash script.
Passing an indirect reference to a function
#!/bin/bash
# ind-func.sh: Passing an indirect reference to a function.
echo_var ()
{
echo "$1"
}
message=Hello
Hello=Goodbye
echo_var "$message" # Hello
# Now, let's pass an indirect reference to the function.
echo_var "${!message}" # Goodbye
echo "-------------"
# What happens if we change the contents of "hello" variable?
Hello="Hello, again!"
echo_var "$message" # Hello
echo_var "${!message}" # Hello, again!
exit 0
Read input from command line
read -s -p "Enter your password for encryption: " pass
echo -n ${pass} | my_encoding_script
Shell script with parameter expansion
Here is a bash script with parameter expansion which used for managing PostgreSQL database. You can use this script as a template to create a script to manage your systems like database, cloud, etc.
#!/bin/bash
[ "$_FAILHARD" == "false" ] || [ "$_FAILHARD" == "False" ] && set +e || set -e
[ "$_DEBUG" == "true" ] || [ "$_DEBUG" == "True" ] && set -x || set +x
# REF LINK: http://mywiki.wooledge.org/BashSheet#Parameter_Operations
export PGHOST="localhost"
export PGUSER=${POSTGRES_USER}
export PGPASSWORD=${POSTGRES_PASSWORD}
usage () {
echo "This script will create new database:
Usage: $(echo $0 | rev | cut -f -1 -d '/' | rev) --database=<database> --db-user=<database-user> --db-password=<database-password>
Options:
- database: database name to be created.
- db-user: the owner of database.
- db-password: the password for database user
"
}
# Get options from command line
for i in "$@"
do
case $i in
--help)
usage && exit
shift
;;
-u=*|--db-user=*)
DB_USER="${i#*=}"
shift
;;
-P=*|--db-password=*)
DB_PASSWORD="${i#*=}"
shift
;;
-d=*|--database=*)
DATABASE="${i#*=}"
shift
;;
*)
# unknown option
;;
esac
done
# Check input parameters
[ -z $DATABASE ] && echo "[+] --database option is needed." && usage && exit 1
[ -z $DB_USER ] && echo "[+] --db-use option is needed." && usage && exit 1
[ -z $DB_PASSWORD ] && echo "[+] --db-password option is needed." && usage && exit 1
# Create database
psql <<EOF
CREATE DATABASE $DATABASE;
CREATE USER $DB_USER WITH ENCRYPTED PASSWORD '$DB_PASSWORD';
ALTER DATABASE $DATABASE OWNER TO $DB_USER;
EOF