Syntax
Define interpreter
#!/bin/bash shebang (#!) with path to interpreterVariables
ANY_VARIABLE=there echo Hello $ANY_VARIABLE
Piping
Take the output of the first command and pass to the next:
ls -l /usr/bin | grep bash Gets a large list of files from /usr/bin then searches all for the bash keywordsTest Operators
[ 5 = 5 ] = 0, 0 means it was executed without issue
[ 3 = 5 ] = 1, 1 means it had one error
[ 1 -eq 1] = 0, This tests the values match but will error if types mismatchIf/Else
if [ ${1,,} = marco ]; then echo "polo!" elif [ ${1,,} = help ]; then echo "say marco to find me" else echo "I'm hidden" fi
Case (Switch)
case ${1,,} in admin | administrator) echo "Hi boss" ;; help) echo "Enter role" ;; *) echo "Not the boss" esac
For Loop
for i in {1..5} do echo "Welcome $i times" done
Functions
showuptime(){ local up=$(uptime -p | cut -c4-) local since=$(uptime -s) cat << EOF ----- This Machine has been up for ${up} It has ben running since ${since} ----- EOF } showuptime
Note: Scope variables locally otherwise they could collide anywhere in the system globally
Vim
i INSERT (Before the cursor)a APPEND (After the cursor)esc Return to command mode:wq write to disc & quit:q! Quit without saving any changesGeneral Terminal
echo <arg> Displays arg parsed in the terminal
cat <file> Displays contents of a file in the terminalbash <filename>.sh Run shell filepwd Print current working directory (More than ~/foo)grep <keyword> <file/place> Search place for keyword
ls -l | grep <keyword> Search keyword in list output echo Foo! > bar.txt Overwrites “Foo” to a file
echo Foo! >> bar.txt Adds “Foo” to a filerm <file> Remove file Misc.
File Permissions
If you receive ‘Permission denied’ when running a file, type
ls -l (To see the extended file info) and note the permissions:
rw-r--r-- 1 fvm staff 1 1 Jan 10:30 shelltest.sh`Now run
chmod u+x <file> (u+x allows the owner to execute the file), note the permission changed:
rwxr--r-- 1 fvm staff 1 1 Oct 10:30 shelltest.sh