Bash Scripting Cheat Sheet

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Bash shell (installed by default)
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Bash Scripting Basics


Here are some of the most basic things to know about Bash scripting. If you are not sure where to start, this would be a good choice.

Syntax Description
#!/bin/bash Shebang that goes on the first line of every Bash script
#!/usr/bin/env bash Alternative (and better) shebang – using environment variable
# Used to make comments, text that comes after it will not be executed
chmod +x script.sh && ./script.sh Give script executable permissions and execute it
$# Stores the number of arguments passed to the Bash script
$1, $2, $3 Variables that store the values passed as arguments to the Bash script
exit Exit from the Bash script, optionally add an error code
Ctrl + C Keyboard combination to stop Bash script in the middle of execution
$( ) Execute a command inside of a subshell
sleep Pause for a specified number of seconds, minutes, hours, or days

Conditional statements

Conditional statements with if or case allow for us to check if a certain condition is true or not. Depending on the answer, the script can proceed different ways.

Syntax Description
if then fi Test a condition and execute the then clause if it is true
if then else fi Execute the then clause if the condition is true, otherwise execute the else clause
if then elif else fi Test multiple conditions and execute whichever clause is true

For case statements it is best to just see a basic example:

#!/bin/bash

day=$(date +"%a")

case $day in 

  Mon | Tue | Wed | Thu | Fri)
    echo "today is a weekday"
    ;;

  Sat | Sun) 
    echo "today is the weekend"
    ;;

  *)
    echo "date not recognized"
    ;; 
esac

If Example:

#!/bin/bash

if [ $1 -eq $2 ]; then
    echo "they are equal"
else
    echo "they are NOT equal"
fi

Bash Loops

Bash loops allow the script to continue executing a set of instructions as long as a condition continues to evaluate to true.

Syntax Description
for do done Continue to loop for a predetermined number of lines, files, etc
until do done Continue to loop until a certain condition is met
while do done Continue to loop as long as a certain condition is true
break Exit the loop and continue to the next part of the Bash script
continue Exit the current iteration of the loop but continue to run the loop

Read User Input

Prompt the user for information to enter by using read command:

#!/bin/bash

read -p "What is your name? " name

echo "Enjoy this tutorial, $name"

Parse input given as arguments to the Bash script:

#!/bin/bash

if [ $# -ne 2 ]; then
    echo "wrong number of arguments entered. please enter two."
    exit 1
fi

echo You have entered $1 and $2.

Arithmetic Operators


Arithmetic operators in Bash give us the ability to do things like addition, subtraction, multiplication, division, and other basic arithmetic inside of a Bash script.

Syntax Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Raise to a power
((i++)) Increment a variable
((i--)) Decrement a variable

Arithmetic Conditional Operators

Arithmetic conditional operators are usually used on two numbers to determine if a certain condition is true or false.

-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=

Note that the operators in the left column will work with single brackets [ ] or double brackets [[ ]], whereas the operators in the right column will work only with double brackets.

String Comparison Operators

We can use string comparison operators to determine if a string is empty or not, and to check if a string is equal, less, or greater in length to another string.

= equal
!= not equal
< less then
> greater then
-n s1 string s1 is not empty
-z s1 string s1 is empty

Bash File Testing Operators

In Bash, we can test to see different characteristics about a file or directory.

-b filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable

Boolean Operators

Boolean operators include and &&, or || and not equal to !. These operators allow us to test if two or more conditions are true or not.

Syntax Description
&& Logical AND operator
|| Logical OR operator
! NOT equal to operator

Informational

Command Syntax Description Example
Who Am I whoami Return username whoami
User ID id Return current user or group ID id
System Information uname [OPTIONS] Display system information uname -a
Manual Pages man [COMMAND] Display manual page for a command man ls
Curl curl [OPTIONS] [URL] Transfer data from or to server curl https://some_website.com
Date date [OPTIONS] Display current date and time date
Find find [DIRECTORY] [OPTIONS] Find files and directories at specified path find /home/user -name '*.txt'
Make Directory mkdir [DIRECTORY] Create new directory mkdir myfolder
Remove Directory rmdir [DIRECTORY] Remove empty directory rmdir myfolder
Process Status ps [OPTIONS] Display process status information ps -ef
Table of Processes top Display live system resource usage top
Disk Usage df [OPTIONS] [FILESYSTEM] Display disk space usage df -h
Create Empty File touch [FILE] Create new file or update timestamp touch myfile.txt
Copy cp [OPTIONS] [SOURCE] [DESTINATION] Copy files or directories from source to destination cp myfile.txt /home/user/documents
Move mv [OPTIONS] [SOURCE] [DESTINATION] Move or rename files and directories mv myfile.txt /home/user/documents
Remove rm [OPTIONS] [FILE/DIRECTORY] Remove files rm my_scratch_file.txt
Remove nonempty directory rm -r path_to_temp_directory
rmdir [OPTIONS] [DIRECTORY] Remove empty directory rmdir path_to_my_directory
Change Mode chmod [OPTIONS] [MODE] [FILE] Change file or directory permissions chmod u+x myfile.txt

Text Files, Networking & Archiving

Command Syntax Description Example
Concatenate cat [FILE] Display the contents of a file cat myfile.txt
Concatentate and display contents of multiple files cat file1 file2
More more [FILE] Display file one screen at a time more myfile.txt
Head head [OPTIONS] [FILE] Display first N lines of file head -5 myfile.txt
Tail tail [OPTIONS] [FILE] Display last N lines of file tail -5 myfile.txt
Echo echo [ARGUMENTS] Display arguments in console echo Hello, World!
Sort sort [OPTIONS] [FILE] Alphanumerically sort file contents sort file.txt
Unique uniq [OPTIONS] [FILE] Report or remove consecutively repeated lines in file uniq file.txt
Word Count wc [OPTIONS] [FILE] Print the number of lines, words, and characters in a file wc file.txt
Grep grep [OPTIONS] PATTERN [FILE] Search for a specified pattern in a file grep "hello" file.txt
Paste paste [OPTIONS] [FILE1] [FILE2] Merge lines of files side by side paste file1.txt file2.txt
Cut cut [OPTIONS] [FILE] Remove sections from each line of a file cut -d":" -f1 /etc/passwd
Tar tar [OPTIONS] [FILE] Archive files together into a single file tar -czvf archive.tar.gz /directory
Zip zip [OPTIONS] [FILE] Compress files into a zip archive zip archive.zip file1.txt file2.txt
Unzip unzip [OPTIONS] [FILE] Uncompress files from a zip archive unzip archive.zip
Hostname hostname Print the name of the current host system hostname
Ping ping [OPTIONS] HOSTNAME/IP Send ICMP ECHO_REQUEST packets to a network host ping google.com
Ifconfig ifconfig [INTERFACE] Display or configure network interface parameters ifconfig
IP ip [OPTIONS] Show or manipulate routing, devices, policy routing, and tunnels ip addr
Curl curl [OPTIONS] URL Transfer data from or to a server curl https://some_website.com
Wget wget [OPTIONS] URL Download files from the web wget https://some_website.com/some_file.txt

Shell Scripting

Command Syntax Description Example
Shebang #!/bin/[shell] First line of shell script #!/bin/bash
Pipe filter1 | filter2 Chain any number of filters ls | sort -r
Locate executable which [EXECUTABLE] Display location of bash executable which bash
Bash bash [SCRIPT] Interpret and run script using Bash shell bash script.txt
Set set [OPTION] List all shell variables set
Define variable [VARIABLE_NAME]=[VALUE] Define shell variable by name and assign value name="John"
Read read [VARIABLE] Read from standard input and store result in variable read name
Env env Print all environment variables and their values env
Export export [VARIABLE] Extend scope of local variable to all child processes export name
Crontab crontab [OPTIONS] Open crontab default editor crontab -e
List all cron jobs crontab -l
Schedule tasks to run at specified times using cron daemon m h dom mon dow command Append date/time to file every Sunday at 6:15 pm 15 18 * * 0 date >> sundays.txt
Back up home directory every Monday at 3:00 am 0 3 * * 1 tar -cvf my_backup_path\my_archive.tar.gz $HOME\
Run shell script first minute of first day of each month 1 0 1 * * ./My_Script.sh