Bash CheatSheet (M122)
Translated from German using DeepL.
Date: September 2021
Reading time: 7 minutes
Help
<command> --helpman <command>Scipts
Test if the name is still free
which scriptNameDetermine line 1
echo $SHELLCreate script (copy first line from previous output)
#!/bin/bashExecution
./scriptName.shRecognize/stop script execution
Show processes
ps -lfAlternatively
topEnd process
kill <PID>Shell variables
| Variable(s) | Meaning |
|---|---|
$0 | Name 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 $n | Arguments 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 $aCalculate
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 $answerif
if [ $1 -eq "hello" ] # see Comparer below
then
echo "world"
else
echo "hh"
fiswitch
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"
;;
esacwhile
exit=0
while [ $exit -ne 1 ]
do
i=0
while [ $i -lt 10 ]
do
echo "."
sleep 1
((i++))
done
$exit=1
donefor
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
donefunction
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
| Vergleicher | Erlä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
| Character | Function |
|---|---|
| ^ | beginning of line |
| $ | end of line |
| ^$ | complete line |
| . | any character |
| * | any number of times |
| .* | any number |
| [] | one character from the range |
Run
bash name
./nameCommand overview
who
Logged in user
whoami
Own username
ls
List files
ls -lachmod
Change permissions
chmod 760 file.txtÜbersicht
| Octal | Decimal | Permission | Representation |
|---|---|---|---|
| 000 | 0 | No Permission | --- |
| 001 | 1 | Execute | --x |
| 010 | 2 | Write | -w- |
| 011 | 3 | Write + Execute | -wx |
| 100 | 4 | Read | r-- |
| 101 | 5 | Read + Execute | r-x |
| 110 | 6 | Read + Write | rw- |
| 111 | 7 | Read + Write + Execute | rwx |
| User | Group | Others |
|---|---|---|
| rwx | rwx | --x |
cp
Copy file(s)
cp text.txt textCopy.txtmv
Rename or move file(s)
cp oldName.txt newName.txtrm
Delete file(s)
rm bad.txtping
ping -c 1touch
Create empty file
touch newFile.txtfind
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_logouthead
Displays the first lines of a file
head -n 4 .bash_logouttail
Displays the last lines of a file
tail -n 3 .bash_logoutnano
Edit files Save:
<CTRL>+Onautilus
Start file manager Open Nautilus
sudo nautilusAttention:
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.txtwc
Count lines, words and characters in a file
wc long.txtOutput:
| lines (-l) | words (-w) | characters (-c) |
|---|---|---|
| 7 | 35 | 220 |
grep
Search file contents If the user is entered
grep -e vmadmin /etc/passwdIn how many lines does vm appear?
grep -c vm /etc/passwdsort
Sort file contents
sort -t ":" -k 2 flowers.txtcut
Cut out file content
cut -d " " -f 1,3 flowers.txttr
Convert file content
tr [:lower:] [:upper:] < flowers.txt
tr -s [:blank:] "\t" < flowers.txtpwd
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.txtAppend result to file
ls >> folderContent.txtShow only hits
find / -name "*usb*.conf" 2>/dev/nullOnly display errors
find / -name "*usb*.conf" 1>found.txtComplete output in the file and no output on the screen
find / -name "*usb*.conf" &>found+error.txtInput 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.txtData 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.txtHelpful 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
}