Bash Scripting

Bash Scripting


Syntax


Define interpreter #!/bin/bash shebang (#!) with path to interpreter
 
Variables
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 keywords
 
Test 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 mismatch
 
If/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 changes
 
 

General Terminal


echo <arg> Displays arg parsed in the terminal cat <file> Displays contents of a file in the terminal
bash <filename>.sh Run shell file
pwd 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 file
rm <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
 

Guides and practical notes, training references, and code snippets shared freely for learning and career growth.