2021
Bash

Bash CheatSheet (M122)

Translated from German using DeepL.

Date: September 2021
Reading time: 7 minutes


Help

<command> --help
man <command>

Scipts

Test if the name is still free

which scriptName

Determine line 1

echo $SHELL

Create script (copy first line from previous output)

#!/bin/bash

Execution

./scriptName.sh

Recognize/stop script execution

Show processes

ps -lf

Alternatively

top

End process

kill <PID>

Shell variables

Variable(s)Meaning
$0Name of the shell script
$$Process number of the shell script
$?Exit status of a shell script; can be set with exit;
$!Process number of the last started background process (started with &)
$1 to $nArguments from the command line
$\*All arguments from the command line in a string
$@All arguments from the command line as individual character strings (array of character strings)
$#Number of all arguments in the command line
$\_Last argument in the command line of the last command called

Assignment in the script

a="Hello World"
counter=0
 
echo $a

Calculate

y=40
echo $[y - 1]

Echo with variables

echo -e "Hello, my name is: $(whoami) \n"
echo -e "My computer is called: $HOSTNAME \n"
echo -e "I am using the bash version: $BASH_VERSION \n"
echo -e "I am currently working in the directory: $PWD \n"
echo -e "I was last in the directory: $OLDPWD \n"
echo -e "Actually my home directory is: $HOME \n"
 
echo "Name of the script (parameter 0): $0"
echo "1st parameter: $1"
 
echo "The file name is: " $(basename $1)
echo "The path is: " $(dirname $1)

Read

read answer
echo $answer

if

if [ $1 -eq "hello" ] # see Comparer below
then
    echo "world"
else
    echo "hh"
fi

switch

echo -n "Enter the name of a country: "
read COUNTRY
 
case $COUNTRY in
	"Switzerland") # string
    	echo -n "Schweiz"
    ;;
 
	[0-9]) # using regex
    	echo -n "any Number"
    ;;
 
	*)
    	echo -n "unknown"
    ;;
esac

while

exit=0
 
while [ $exit -ne 1 ]
do
 
  i=0
  while [ $i -lt 10 ]
  do
    echo "."
    sleep 1
    ((i++))
  done
 
  $exit=1
done

for

for i in {0..3} # for item in [LIST]
do
  echo "Number: $i"
done
 
# declaring array:
BOOKS=("In Search of Lost Time" "Don Quixote" "Ulysses" "The Great Gatsby")
for book in "${BOOKS[@]}"; do
  echo "Book: $book"
done
 
# using i:
for ((i = 0 ; i <= 1000 ; i++)); do
  echo "Counter: $i"
done
 
# using files:
for file in /home/vmadmin/Desktop/M122; do
    echo $file
done

function

function hello_world {
  echo "hello world"
}
 
globalVar="change me"
 
hello_user () {
  # param: $1 - firstname
  # param: $2 - lastname
  local localVar=10
  globalVar="changed"
 
  echo "hello $1 $2"
 
  return 0 # only numeric - else use global vars
}
 
# call function -> without `()`
hello_world
hello_user "john" "doe"
# access return value
echo $?

Operationen

VergleicherErläuterung
! Die EXPRESSION ist falsch.
-n Die Länge von STRING ist grösser als Null.
-z Die Länge von STRING ist Null (d.h. sie ist leer).
= STRING1 ist gleich STRING2
!= STRING1 ist ungleich STRING2
-eq INTEGER1 ist numerisch gleich INTEGER2
-gt INTEGER1 ist numerisch grösser als INTEGER2
-lt INTEGER1 ist numerisch kleiner als INTEGER2
-d FILE exists and is a directory.
-e FILE exists.
-r FILE exists and the read permission is granted.
-s FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE exists and the write permission is granted.
-x FILE exists and the execute permission is granted.

Regex

grep "<regex expression>" <file>

Operations

CharacterFunction
^beginning of line
$end of line
^$complete line
.any character
*any number of times
.*any number
[]one character from the range

Run

bash name
./name

Command overview

who

Logged in user

whoami

Own username

ls

List files

ls -la

chmod

Change permissions

chmod 760 file.txt

Übersicht

OctalDecimalPermissionRepresentation
0000No Permission---
0011Execute--x
0102Write-w-
0113Write + Execute-wx
1004Readr--
1015Read + Executer-x
1106Read + Writerw-
1117Read + Write + Executerwx
UserGroupOthers
rwxrwx--x

cp

Copy file(s)

cp text.txt textCopy.txt

mv

Rename or move file(s)

cp oldName.txt newName.txt

rm

Delete file(s)

rm bad.txt

ping

ping -c 1

touch

Create empty file

touch newFile.txt

find

Search for files and directories

find /Downloads -user root -name "*file*"

* -> any number of characters
? -> any single character
[] -> delimited characters (find /Desktop -name designVersion[1-2].txt)

cat

Output contents of a file

cat .bash_logout

head

Displays the first lines of a file

head -n 4 .bash_logout

tail

Displays the last lines of a file

tail -n 3 .bash_logout

nano

Edit files Save:

<CTRL>+O

nautilus

Start file manager Open Nautilus

sudo nautilus

Attention:
If you create new folders and files as root in the graphical file manager nautilus, root becomes the new owner (and not vmadmin). You can correct this with chown and chgrp:

sudo chown vmadmin newFile.txt
sudo chgrp vmadmin newFile.txt

wc

Count lines, words and characters in a file

wc long.txt

Output:

lines (-l)words (-w)characters (-c)
735220

grep

Search file contents If the user is entered

grep -e vmadmin /etc/passwd

In how many lines does vm appear?

grep -c vm /etc/passwd

sort

Sort file contents

sort -t ":" -k 2 flowers.txt

cut

Cut out file content

cut -d " " -f 1,3 flowers.txt

tr

Convert file content

tr [:lower:] [:upper:] < flowers.txt
tr -s [:blank:] "\t" < flowers.txt

pwd

Current directory

mkdir

Create folder

rmdir

Delete an empty directory

rm -r

Delete a directory

diff

Compare 2 files

du

Displays used disk space

ps

Displays processes

ps -Alf

(Displays the processes, sorted by process identification number (PID))

Redirection

Output redirection

Write result to file

ls > folderContent.txt

Append result to file

ls >> folderContent.txt

Show only hits

find / -name "*usb*.conf" 2>/dev/null

Only display errors

find / -name "*usb*.conf" 1>found.txt

Complete output in the file and no output on the screen

find / -name "*usb*.conf" &>found+error.txt

Input redirection

As input data, you can send data from a file to a command with < instead of entering it on the keyboard (standard input).

dc < datei.txt

|

Data transfer WITHOUT pipe

cut -d " " -f2,4 flowers.txt > tmp.txt
sort -n -k2 tmp.txt

Data forwarding with Pipe

cut -d " " -f2,4 flowers.txt | sort -n -k2

()

Command substitution with brackets

ls -l $(find /sys/class/sound -name "*seq*")

tee

Duplicate output

cut -d " " -f 1,3 blumenartikel.txt | tee outputblumen.txt

Helpful functions

function is_num { # string - string to test
	REGEX="^[0-9]+$"
	if [[$1 =~ $REGEX]]; then
	true
	else
	false
	fi
}
 
function is_decimal { # string - string to test
	REGEX="^[0-9]+(\.[0-9]+$|$)"
	if [[$1 =~ $REGEX]]; then
	true
	else
	false
	fi
}
 
function is*str { # string - string to test
	REGEX="[A-Za-z0-9*]+"
	if [[$1 =~ $REGEX]]; then
	true
	else
	false
	fi
}
 
function file_exists { # file
	if [[-f "$1" && -n "$1"]]; then
	true
	else
	false
	fi
}
 
function folder_exists { # folder
	if [[-d "$1" && -n "$1"]]; then
	true
	else
	false
	fi
}
 
function files_are_equal { # file - file 1 # file - file 2
	diff $1 $2 &>/dev/null
	return $?
}
 
function file_contains { # file # expression - regex expression
	grep -e $2 $1 &>/dev/null
	return $?
}
 
function folder_empty { # folder - foldername
	if [[-z "$(ls $1 2>/dev/null)"]]; then
	true
	else
	false
	fi
}
 
function folder_contains { # folder # expression - or filename
	find $1 -printf "%f\n" | grep -e $2 &>/dev/null
	return $?
}
 
function kill_process { # string - process name
	kill $(ps -Alf | grep "$1" | tr -s [:blank:] "\t" | head -n1 | cut -f4) &>/dev/null
	return $?
}
 
function get_file_line { # file # line - line number
	sed "$2q;d" $1
}
 
USER_INPUT=""
function get_input { # string - prompt to show
	echo -n "$1: "
		read
		USER_INPUT=$REPLY
}
 
function read_confirmation {
	read -p "Do you want to continue? [Y/n] " -n 1 -r
	REGEX="^[Yy]$"
	if [[$REPLY =~ $REGEX]]; then
	true
	else
	false
	fi
}
 
function set_var { # string - var name # string - var value
	printf -v "$1" "%s" "$2"
}
 
function get_filename { # string - full file path
	basename $1
}
 
function validate_param { # string - var name # string - var value
	if [[$1 =~ _dir$]]; then
	folder_exists $2
			return $?
		elif [[ $1 =~ _file$ ]]; then
	file_exists $2
			return $?
		elif [[ $1 =~ _num$ || $1 =~ _int$ ]]; then
	is_num $2
			return $?
		elif [[ $1 =~ _decimal$ || $1 =~ _dec$ ]]; then
	is_dec $2
			return $?
		elif [[ $1 =~ _string$ || $1 =~ _str$ ]]; then
	is_str $2
	return $?
	fi
}
 
function validate_params {
	for i in ${!PARAMS[@]}; do
			param=${PARAMS[$i]}
	value=${!param}
	if ! $(validate_param $param $value); then
		print_usage
		script_error
	fi
	done
}
 
function script_error {
	exit 1
}
 
function script_success {
	exit 0
}
 
function print_usage {
	echo "usage: $0 ${PARAMS[*]}" # string / num / decimal / dir / file
}