The Command Line should be a developer's best friend, but many times it sits there, sad and lonely as we use to call other programs. Behind that unassuming little blinking cursor is an entire world of productivity, just waiting to be strung together. There is even an entire scripting language hidden underneath that is just waiting for you to use it! Let's investigate BASH, the shell that's syntax is universal across almost all systems (and find out why your Linux scripts do not always work on OSX).
3. Midwest PHP 2018
What is Bash?
●
Bourne Shell
– Introduced with Unix System 7 in 1977
– Still present on most systems as `sh`
●
Bourne Again Shell
– 1989 as part of the GNU Project
– Also took parts from C Shell (`csh`) and Korn Shell (`ksh`)
– Added syntactic sugar on top of the Bourne Shell
3
4. Midwest PHP 2018
Run directly or through scripts
$ for FILE in `ls`; do echo ${FILE}; done
#!/bin/bash
for FILE in `ls`; do
echo ${FILE}
done
4
5. Midwest PHP 2018
Why use Bash?
●
System Scripts
●
Quick prototyping
●
Ultra-portable scripts*
5
13. Midwest PHP 2018
Built In Variables
$BASH = Location of the bash executable
$FUNCNAME = Name of the current function
$HOME = Home directory of current user
$PATH = Search path for binaries
$PWD = Current working directory
$TMOUT = Time before a script times out
$UID = Current User ID
13
14. Midwest PHP 2018
Built In Variables
$0, $1, … = Positional Parameters
$# = Number of arguments
“$@” = All arguments as quote delimited words
$! = PID of the last job run in background
$? = Exit code of the last command
$$ = PID of the script itself
http://tldp.org/LDP/abs/html/internalvariables.html
14
16. Midwest PHP 2018
Numerical Comparison Operators
-eq - Equal To
-ne - Not Equal To
-gt, > - Greater Than
-ge, >= - Greater Than or Equal
-lt, < - Less Than
-le, <= - Less Than or Equal
16
17. Midwest PHP 2018
String Comparison Operators
==, = - Equal To
!= - Not Equal
< - Less than ASCII order
> - Greater than ASCII order
-n - Not null
-z - Is Null, 0 length
17
31. Midwest PHP 2018
Structuring Larger Scripts
●
Define functions at the top
●
Break functions out into their own files
– source filename.sh
31
32. Midwest PHP 2018
Function-Only Scripts
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
# This script is being invoked as a script
echo 'This script is not intended to be run standalone. Please use with
the system-micro.sh script'
exit 1
fi
32