Bash scripting cheatsheet

The ability to automate tasks with Bash scripts in Linux is one of the operating system’s most powerful components.

Bash scripting cheatsheet

However, due to the sheer amount of scripting components, it can be intimidating for newcomers. Even long-time users can sometimes forget something and that’s why we’ve made this bash scripting cheat sheet. For such times, it is very useful to have a compiled list of bash scripting components sorted by category. That way, whenever you forget the exact syntax of an operator, conditional statement, etc., it only takes a few moments to refer to the list. In this tutorial, we will present you a curated list of the most useful things to know for bash scripting. These are some of the most useful elements, but they are not easy to remember for everyone.Next time your mind is blanking when writing a Bash script, take a look at the Bash scripting cheat sheet below for some quick help.

CategoryRequirements, Conventions or Software Version Used
SystemAny Linux distro
SoftwareBash shell (installed by default)
OtherPrivileged 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. This would be a good option if you’re not sure where to start.

SyntaxDescription
#!/bin/bashShebang that goes on the first line of every Bash script
#!/usr/bin/env bashAlternative (and better) shebang – using environment variable
#Used to make comments, text that comes after it will not be executed
chmod +x script.sh && ./script.shGive script executable permissions and execute it
$#Stores the number of arguments passed to the Bash script
$1, $2, $3Variables that store the values passed as arguments to the Bash script
exitExit from the Bash script, optionally add an error code
Ctrl + CKeyboard combination to stop Bash script in the middle of execution
$( )Execute a command inside of a subshell
sleepPause 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.

SyntaxDescription
if then fiTest a condition and execute the then clause if it is true
if then else fiExecute the then clause if the condition is true, otherwise execute the else clause
if then elif else fiTest 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

Basic if example script:

#!/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.

SyntaxDescription
for do doneContinue to loop for a predetermined number of lines, files, etc
until do doneContinue to loop until a certain condition is met
while do doneContinue to loop as long as a certain condition is true
breakExit the loop and continue to the next part of the Bash script
continueExit 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.

SyntaxDescription
+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 s1string s1 is not empty
-z s1string s1 is empty

Bash File Testing Operators

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

-b filenameBlock special file
-c filenameSpecial character file
-d directorynameCheck for directory existence
-e filenameCheck for file existence
-f filenameCheck for regular file existence not a directory
-G filenameCheck if file exists and is owned by effective group ID.
-g filenametrue if file exists and is set-group-id.
-k filenameSticky bit
-L filenameSymbolic link
-O filenameTrue if file exists and is owned by the effective user id.
-r filenameCheck if file is a readable
-S filenameCheck if file is socket
-s filenameCheck if file is nonzero size
-u filenameCheck if file set-ser-id bit is set
-w filenameCheck if file is writable
-x filenameCheck 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.

syntaxDescription
&&Logical AND operator
||Logical OR operator
!NOT equal to operator
Mahesh Wabale
Latest posts by Mahesh Wabale (see all)

Leave a Comment