Bash Scripting
Resources
Tutorials/ Getting Started
shellscript.sh "shell scripting tutorial"
BashGuide "aid people interested in learning to work with BASH"
Reference
Cheatsheet devhints.io
Tips & Tricks
Shell Scripts Matter "a summary of everything that can, and should be done when writing shell scripts."
ShellCheck "static analysis tool for shell scripts"
Unofficial Bash Strict Mode "causes bash to behave in a way that makes many classes of subtle bugs impossible."
Talks
General Advice
bash is not sh
While bash
is "sh-compatible" some features of bash
will break or cause unexpected behaviour in sh
.
Read bash Is Not sh for a more detailed explanation.
Forget the .sh extension
Don't give scripts an .sh
extension.
The Google Shell Style Guide advises against it unless it's a library
It's a
bash
script, not ansh
script
Pipes
grep
If you're piping to grep
multiple times only the last grep
in the sequence can be called with -q
.
Examples
Shebang
First line of the script that indicates which interpreter is used to execute the file. The #!
must be at the very start of the file, with no spaces or blank lines before it.
"
#!/usr/bin/env
searchesPATH
forbash
, andbash
is not always in/bin
, particularly on non-Linux systems."
"This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it."
Execute Script
Execute bash
and tell it to read the script myscript
. When executing the script this way the shebang line (#!
) is just a comment, bash
does nothing with it
We can give the script executable permission. Instead of calling bash
manually, we can execute myscript
directly.
When myscript
is executed this way, the shebang line (#!
) is used to determine which interpreter to use.
Debug Mode
Print every command before its execution, replacing the variables with their real values.
Unofficial Strict Mode
Last updated