# Bash scripting cheatsheet * by Lee2sman * Updated 2017-09-18 # Bash shebang * ```#!/usr/bin/env bash``` for portability, or less good, ```#!/bin/bash``` # Commenting ```# this symbol makes everything after it on a line a comment``` # Variables * No data types. Number, char, string, ok! * No need to declare. Just assign a value to create it. * Get the value of a variable (whatever is stored in it) by calling it with ```$``` in front. * declare a local variable in a function by saying ```local``` before creating it. ### Builtin shell variables ``` $0 #Name of this shell script itself. $1 #Value of first command line parameter (similarly $2, $3, etc) $# #In a shell script, the number of command line parameters. $* #All of the command line parameters. $- #Options given to the shell. $? #Return the exit status of the last command. $$ #Process id of script (really id of the shell running the script) ``` # File redirection and Piping * Three default files: 0. standard input (stdin), 1. standard output (stdout) and 2. standard error (stderr) * ```> filename``` redirects stdout to a file (and creates the file if it didn't already exist) * ```>> filename``` redirects stdout to a file but it *appends* to the end of the file if it already exists * ```|``` is the pipe. **Piping** is used to chain commands, scripts, files and programs together. * Piping allows for robust mini programs to be built together like lego kits of separate parts * Example ```cat *.txt | sort | uniq > result-file``` Sorts the output of all the .txt files and deletes duplicate lines, saving outcome to *result-file* # Input * ```read``` command e.g. ```read num``` asks for input and puts it in $num # Arithmetic * uses the ```expr``` command ``` result=`expr $1 + 2` result2=`expr $2 + $1 / 2` result=`expr $2 \* 5` #note the \ on the * symbol ``` # Conditionals * Usually surround comparisons and conditions in brackets not parens e.g. ```if [ $# -gt 1 ]``` * ```&&``` is logical *and*, ```||``` is logical *or* ## Comparisons ### Booleans ``` ! #not -a #and -o #or ``` ### Numerical comparisons ``` -eq == equal to -ne ≠ (not equal to) -gt > greater than -ge >= greather than or equal to -lt < less than -le <= less than or equal to < less than <= less than or equal to ((within double parenthesis)) > greater than ((within double parenthesis)) >= greater than or equal to ((within double parenthesis)) = equal to, including for strings, e.g. ```if [ "$a" = "$b" ]``` ``` ### STRING COMPARISONS ``` == is equal to != is NOT equal to < less than (ascii-betically) > greater than (ascii-betically) -z string is null -n string is not null ``` ### Example comparisons ``` if [ "$VAR1" = "$VAR2" ]; then echo "expression evaluated as true" else echo "expression evaluated as false" fi ``` ``` case "$C" in "1") do_this() ;; "2" | "3") do_what_you_are_supposed_to_do() ;; *) #fallback default case do_nothing() ;; esac ``` # Looping * Iterates over a string of values ``` ### FOR loop for i in 1 2 3 4 5 # can also be written for i in {1..5} or {start..end..increment} do echo "Welcome $i times" done ``` * ```select``` looping works just like ```for``` * with select, use p3 prompt. User options get a number prefix and waits for number response. ## Example - Basic text menu ``` #!/bin/bash OPTIONS="Hello Quit" select opt in $OPTIONS; do if [ "$opt" = "Quit" ]; then echo done exit elif [ "$opt" = "Hello" ]; then echo Hello World else clear echo bad option fi done ``` ### WHILE loop ``` while [ condition ] do command done ``` ``` ### UNTIL loop until [ condition ] # executes until condition = true do command done ``` # Functions * works same as other languages * can take parameters ``` function e { echo $1 } e Hello #will echo Hello when called ``` # Debugging ```#!/bin/bash -x``` Adding ```-x``` to the shebang produces output information # Additional shell features ``` $var #Value of shell variable var. ${var}abc #Example: value of shell variable var with string abc appended. # #At start of line, indicates a comment. var=value #Assign the string value to shell variable var. cmd1 && cmd2 #Run cmd1, then if cmd1 successful run cmd2, otherwise skip. cmd1 || cmd2 #Run cmd1, then if cmd1 not successful run cmd2, otherwise skip. cmd1; cmd2 #Do cmd1 and then cmd2. cmd1 & cmd2 #Do cmd1, start cmd2 without waiting for cmd1 to finish. (cmds) #Run cmds (commands) in a subshell. ``` * Additional shell features from this [Bash cheatsheet](http://johnstowers.co.nz/pages/bash-cheat-sheet.html)