Nuances in Shell Scripting
Shell
Programming
Shell’s just another programming language.
Variables
- Variables are denoted by
$
foo = bar
fails since spaces denote argumentsecho '$foo'
outputs$foo
echo "$foo"
outputsbar
Reserved Variables
- Reserve variables include, but are not limited to:
$0
: name of the script$1
to$9
: arguments passed to the script
$#
: number of arguments passed to the script$@
: all arguments passed to the script$?
: exit status of the last command$_
: last argument of the previous command; can also be accessed byEsc + .
oralt + .
$$
: process ID (pid) of the current script!!
: rerun the entire last command
Command and Process Substitutions
- Command/process substitutions are like f-strings in Python
- Difference between command and process substitution is that the latter will place the output in a temporary file
- Command substitution:
$(command)
- Process substitution:
<(command)
Comparisons and Brace Expansions
- When doing comparisons in bash, use
[[ ]]
rather than[ ]
; apparently, chances of mistakes are lower this way - Use
{}
for common substrings in commandsconvert image.{png,jpg}
cp /path/to/project/{foo,bar,baz}.sh /newpath
mv *{.py,.sh} folder
touch {foo,bar}/{a..h}
Functions vs Scripts
- Functions are executed in the current environment, whereas scripts aren’t
- Thus, functions can modify environment variables whereas scripts can’t
- Scripts can only access environment variables that are exported with export