programming

Bash Script Cheat Sheet

Bash scripting cheat sheet covering variables, loops, conditionals, parameters, and functions. Quick reference for offensive ops and automation.

Sep 21, 2024·6 min read·By Jobyer Ahmed

Hello Bytium

#!/usr/bin/bash
#This is Comment

echo "Hello Bytium"
printf "Hello Bytium"

Save as hello.sh , give it execute permission chmod +x hello.sh and run ./hello.sh

Parameters

#!/usr/bin/bash
#This is Comment

echo -e "Hello $1"
printf "Hey, how is it goin $1?"
echo ""

$1 is the first parameters, second parameters should be $2 and so on.

Variables

Variables used to store data to use in future by referencing to the variable name! There are 4 type of variable we can use in bash. We can’t use Reserved word for variable names. Reserved words are:

if    
then    
elif    
else    
fi    
time
for    
in    
until    
while    
do    
done
case    
esac    
coproc    
select    
function
{    }   
[[    ]]  
!
  1. Integer: These are numeric variables
  2. String: “Text based variable”
  3. Constant: “These variable Can’t be modified”
  4. Array: “Index of variable”

Integer Variable

#!/bin/bash

##Integer Variable
job=$3
name=$1

#Integer Variable
exp=5 

echo "$name having $exp+ experience in $job"
echo ""

String Variable

String variable is double quoted

#!/bin/bash

##String Variable
name="Bytium"
owner="Your name"

echo "The owner of $name is $owner"
echo "This is concated string: $name$owner"

Constant Variable

We can’t modify the variable. Two way to declare :

  1. Using declare -r
  2. Using readonly
##String Variable
readonly name="Bytium"

declare -r var="You"
var="Me"
readonly name2="Red Teaming"
name2="Blue Teaming"

echo $name2

echo $var

Execute in terminal and see the live result.

Array Variable

More details on Appropriate chapter

Internal Variables

$ echo $BASH
/usr/bin/bash

$ echo $BASH_SUBSHELL
0
$ echo $BASHPID #Process ID of current bash
46990

#Effective User ID
$ echo $EUID
1000

#Groups of current user
$ echo $GROUPS
1000

#Home directory of current user
$ echo $HOME
/home/Bytium

#Hostname
$ echo $HOSTNAME
debian

#Machine Type
$ echo $MACHTYPE
x86_64-pc-linux-gnu

#OLD Path
$ echo $OLDPWD
/home/Bytium

#OS Type
$ echo $OSTYPE
linux-gnu

#Binary Paths
$ echo $PATH
/home/Bytium/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin

#Current PROMPT
$ echo $PS1
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$

#Change Prompt
$ export PS1="Bytium$"
Bytium$

#Current Directory
$ echo $PWD
/home/Bytium

#User ID
$ echo $UID
1000

#Process ID of last command
$ echo $!

#Exit status of last command
$ echo $?
0

Command Substitutions

Two we can substitute command

  1. Using double backqoute “Command_Here
  2. Using $(Command_here)
##Using backquote
passwd=`cat /etc/passwd`

##Using $ sign with first bracket
shadow="$(cat /etc/shadow)" #Without root, permission denied
issue="$(cat /etc/issue)"

#display contents
echo $passwd 
echo $shadow
echo $issue

Operators

Here is the some list of commonly used operators

OperatorExampleDescription
=variable=1, var2="Bytium"Assign Variable.
+,-,/,*var1=1;var1=2;var3=$((var1+var2))Arithmetic Operator
+=, -=, *=, /=var+=1, var-=1, var*=2, var/=2Increment by +1, Decrement by -1, Multiply by 2, divide by 2
&bitwish AND
!if [ ! -f $FILE]Not Operator
&&$condition1 && $condition2And Operator
||`$con1

Arrays

Bash support one-dimensional indexed. And the array index always start from 0. Way to declare an array:

  1. declare -a array_name
  2. Declare as variable but values in first brackets arr1=(One two three)
  3. Another way is declare -a array_name=(one two three)
#!/usr/bin/bash

#Array Variables
declare -a arr1
arr1=("One Two Three" "Two" "Three")
echo ${arr1[0]}

To reference the array we need to use ${array_name[number]}

Conditional

Conditional is a test. This mean, parametrically test for Fail and Success Status and divert the execution somewhere! Bash also has primary expression for conditional statements!

Primary Expression

ExpressionDescription
-a fileTrue if file exist
-b fileTrue if file exist and a block file
-c fileTrue if exist and it is a character special file
-d fileTrue if it is a directory file
-e fileTrue if file exist
-h fileTrue if it is exist and a symbolic file
-k fileTrue if it is exist and a sticky bit is set
-r fileTrue if the file exist and Readable
-s fileTrue if the file size is greater than 0
-w fileTrue if File Exist and Writable
-x fileTrue if File Exist and executable
-G fileTrue if file exists and is owned by the effective group id.
-L fileTrue if file exists and is a symbolic link.
-N fileTrue if file exists and has been modified since it was last read.
-O fileTrue if file exists and is owned by the effective user id.
-S fileTrue if file exists and is a socket.
-z stringTrue if the length of string is zero.
string1 == string2, string1 = string2True if the strings are equal.
string1 != string2True if the strings are not equal.
string1 < string2True if string1 sorts before string2 lexicographically.
string1 > string2True if string1 sorts after string2 lexicographically.
-eqEqual
-neNot Equal
-leless than
-gtgreater than

if/then

#!/usr/bin/bash

if [ $UID -ne 0 ]
then
        echo "Run as root!!!"

fi

if/then/else

#!/usr/bin/bash

if [ $UID -ne 0 ]
then
        echo "Run as root!!!"

else 
        echo "You are root"

if/then/elif/else

To catch elif the if condition need to be false

#!/usr/bin/bash

user=$UID

if [ $user -eq 0 ] #False
then
        echo "You are root!!!"

elif [ $user -eq 1000 ] #True. If false execute else statement
then
        warning=$(id -un $user)
        echo "Nice try Mr.$warning"

else 
        echo "You are dumb!!!"
fi

Loop

Example 1:

#!/usr/bin/bash

#First example
for i in {1..10}
do
    echo $i
done

Example 2:

#!/usr/bin/bash

#First example
for i in $(ls)
do
        t=`echo $i | grep ".old"`
        if [ $t ]
        then
                echo "Deleting $t"
                rm $t
        fi
done

Example 3:

#!/usr/bin/bash

#First example
for i in $(cat words)
do
        host $i.google.com | grep "has address"
done

Functions

#!/usr/bin/bash

echo -n "Word list: "

read words #Take input from users
target=$1 #Possitional Parameters

#Declare the Function
getip(){

for i in $(cat words)
do
        host $i.$target | grep "has address"
done

}

#Call the function
getip

Input/Output Redirections

Save to file

cat /etc/passwd|grep '/bin/bash'>active_user

Read from file

cat < words.txt

Redirect the output

cat /etc/passwd | grep '/bin/bash'

Regular Expression

System Commands

It is not finished yet!