13 - Conditional execution
14 - Command substitution
24 This is a quick reference to getting started with Bash scripting.
26 - [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
27 - [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
51 echo "Hi $NAME" #=> Hi John
52 echo 'Hi $NAME' #=> Hi $NAME
63 See [Command substitution](http://wiki.bash-hackers.org/syntax/expansion/cmdsubst)
65 ### Conditional execution
68 git commit && git push
69 git commit || echo "Commit failed"
73 {: id='functions-example'}
80 echo "You are $(get_name)"
83 See: [Functions](#functions)
86 {: id='conditionals-example'}
89 if [[ -z "$string" ]]; then
90 echo "String is empty"
91 elif [[ -n "$string" ]]; then
92 echo "String is not empty"
96 See: [Conditionals](#conditionals)
105 See: [Unofficial bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
113 | Expression | Description |
114 | ---------- | ------------------- |
115 | `{A,B}` | Same as `A B` |
116 | `{A,B}.js` | Same as `A.js B.js` |
117 | `{1..5}` | Same as `1 2 3 4 5` |
119 See: [Brace expansion](http://wiki.bash-hackers.org/syntax/expansion/brace)
131 echo ${name/J/j} #=> "john" (substitution)
132 echo ${name:0:2} #=> "Jo" (slicing)
133 echo ${name::2} #=> "Jo" (slicing)
134 echo ${name::-1} #=> "Joh" (slicing)
135 echo ${name:(-1)} #=> "n" (slicing from right)
136 echo ${name:(-2):1} #=> "h" (slicing from right)
137 echo ${food:-Cake} #=> $food or "Cake"
142 echo ${name:0:length} #=> "Jo"
145 See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
148 STR="/path/to/foo.cpp"
149 echo ${STR%.cpp} # /path/to/foo
150 echo ${STR%.cpp}.o # /path/to/foo.o
151 echo ${STR%/*} # /path/to
153 echo ${STR##*.} # cpp (extension)
154 echo ${STR##*/} # foo.cpp (basepath)
156 echo ${STR#*/} # path/to/foo.cpp
157 echo ${STR##*/} # foo.cpp
159 echo ${STR/foo/bar} # /path/to/bar.cpp
164 echo ${STR:6:5} # "world"
165 echo ${STR: -5:5} # "world"
169 SRC="/path/to/foo.cpp"
170 BASE=${SRC##*/} #=> "foo.cpp" (basepath)
171 DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
176 | Code | Description |
177 | ----------------- | ------------------- |
178 | `${FOO%suffix}` | Remove suffix |
179 | `${FOO#prefix}` | Remove prefix |
181 | `${FOO%%suffix}` | Remove long suffix |
182 | `${FOO##prefix}` | Remove long prefix |
184 | `${FOO/from/to}` | Replace first match |
185 | `${FOO//from/to}` | Replace all |
187 | `${FOO/%from/to}` | Replace suffix |
188 | `${FOO/#from/to}` | Replace prefix |
193 # Single line comment
206 | Expression | Description |
207 | --------------- | ------------------------------ |
208 | `${FOO:0:3}` | Substring _(position, length)_ |
209 | `${FOO:(-3):3}` | Substring from the right |
213 | Expression | Description |
214 | ---------- | ---------------- |
215 | `${#FOO}` | Length of `$FOO` |
221 echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
222 echo ${STR,,} #=> "hello world!" (all lowercase)
225 echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
226 echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
231 | Expression | Description |
232 | ----------------- | -------------------------------------------------------- |
233 | `${FOO:-val}` | `$FOO`, or `val` if unset (or null) |
234 | `${FOO:=val}` | Set `$FOO` to `val` if unset (or null) |
235 | `${FOO:+val}` | `val` if `$FOO` is set (and not null) |
236 | `${FOO:?message}` | Show error message and exit if `$FOO` is unset (or null) |
238 Omitting the `:` removes the (non)nullity checks, e.g. `${FOO-val}` expands to `val` if unset otherwise `$FOO`.
247 for i in /etc/rc.*; do
255 for ((i = 0 ; i < 100 ; i++)); do
271 for i in {5..50..5}; do
279 cat file.txt | while read line; do
296 ### Defining functions
305 # Same as above (alternate syntax)
319 local myresult='some value'
346 | Expression | Description |
348 | `$#` | Number of arguments |
349 | `$*` | All positional arguments (as a single word) |
350 | `$@` | All positional arguments (as separate strings) |
351 | `$1` | First argument |
352 | `$_` | Last argument of the previous command |
354 **Note**: `$@` and `$*` must be quoted in order to perform as described.
355 Otherwise, they do exactly the same thing (arguments as separate strings).
357 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
365 Note that `[[` is actually a command/program that returns either `0` (true) or `1` (false). Any program that obeys the same logic (like all base utils, such as `grep(1)` or `ping(1)`) can be used as condition, see examples.
367 | Condition | Description |
369 | `[[ -z STRING ]]` | Empty string |
370 | `[[ -n STRING ]]` | Not empty string |
371 | `[[ STRING == STRING ]]` | Equal |
372 | `[[ STRING != STRING ]]` | Not Equal |
374 | `[[ NUM -eq NUM ]]` | Equal |
375 | `[[ NUM -ne NUM ]]` | Not equal |
376 | `[[ NUM -lt NUM ]]` | Less than |
377 | `[[ NUM -le NUM ]]` | Less than or equal |
378 | `[[ NUM -gt NUM ]]` | Greater than |
379 | `[[ NUM -ge NUM ]]` | Greater than or equal |
381 | `[[ STRING =~ STRING ]]` | Regexp |
383 | `(( NUM < NUM ))` | Numeric conditions |
387 | Condition | Description |
388 | -------------------- | ------------------------ |
389 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
391 | `[[ ! EXPR ]]` | Not |
392 | `[[ X && Y ]]` | And |
393 | `[[ X || Y ]]` | Or |
397 | Condition | Description |
399 | `[[ -e FILE ]]` | Exists |
400 | `[[ -r FILE ]]` | Readable |
401 | `[[ -h FILE ]]` | Symlink |
402 | `[[ -d FILE ]]` | Directory |
403 | `[[ -w FILE ]]` | Writable |
404 | `[[ -s FILE ]]` | Size is > 0 bytes |
405 | `[[ -f FILE ]]` | File |
406 | `[[ -x FILE ]]` | Executable |
408 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
409 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
410 | `[[ FILE1 -ef FILE2 ]]` | Same files |
416 if [[ -z "$string" ]]; then
417 echo "String is empty"
418 elif [[ -n "$string" ]]; then
419 echo "String is not empty"
421 echo "This never happens"
427 if [[ X && Y ]]; then
434 if [[ "$A" == "$B" ]]
443 if (( $a < $b )); then
444 echo "$a is smaller than $b"
449 if [[ -e "file.txt" ]]; then
460 Fruits=('Apple' 'Banana' 'Orange')
469 ### Working with arrays
472 echo ${Fruits[0]} # Element #0
473 echo ${Fruits[-1]} # Last element
474 echo ${Fruits[@]} # All elements, space-separated
475 echo ${#Fruits[@]} # Number of elements
476 echo ${#Fruits} # String length of the 1st element
477 echo ${#Fruits[3]} # String length of the Nth element
478 echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
479 echo ${!Fruits[@]} # Keys of all elements, space-separated
485 Fruits=("${Fruits[@]}" "Watermelon") # Push
486 Fruits+=('Watermelon') # Also Push
487 Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
488 unset Fruits[2] # Remove one item
489 Fruits=("${Fruits[@]}") # Duplicate
490 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
491 lines=(`cat "logfile"`) # Read from file
497 for i in "${arrayName[@]}"; do
519 Declares `sound` as a Dictionary object (aka associative array).
521 ### Working with dictionaries
524 echo ${sounds[dog]} # Dog's sound
525 echo ${sounds[@]} # All values
526 echo ${!sounds[@]} # All keys
527 echo ${#sounds[@]} # Number of elements
528 unset sounds[dog] # Delete dog
533 #### Iterate over values
536 for val in "${sounds[@]}"; do
541 #### Iterate over keys
544 for key in "${!sounds[@]}"; do
555 set -o noclobber # Avoid overlay files (echo "hi" > foo)
556 set -o errexit # Used to exit upon error, avoiding cascading errors
557 set -o pipefail # Unveils hidden failures
558 set -o nounset # Exposes unset variables
564 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
565 shopt -s failglob # Non-matching globs throw errors
566 shopt -s nocaseglob # Case insensitive globs
567 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
568 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
571 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
579 | Command | Description |
580 | --------------------- | ----------------------------------------- |
581 | `history` | Show history |
582 | `shopt -s histverify` | Don't execute expanded result immediately |
586 | Expression | Description |
587 | ------------ | ---------------------------------------------------- |
588 | `!$` | Expand last parameter of most recent command |
589 | `!*` | Expand all parameters of most recent command |
590 | `!-n` | Expand `n`th most recent command |
591 | `!n` | Expand `n`th command in history |
592 | `!<command>` | Expand most recent invocation of command `<command>` |
596 | Code | Description |
597 | -------------------- | --------------------------------------------------------------------- |
598 | `!!` | Execute last command again |
599 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
600 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
601 | `!$:t` | Expand only basename from last parameter of most recent command |
602 | `!$:h` | Expand only directory from last parameter of most recent command |
604 `!!` and `!$` can be replaced with any valid expansion.
608 | Code | Description |
609 | -------- | ---------------------------------------------------------------------------------------- |
610 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
611 | `!^` | Expand first argument from most recent command |
612 | `!$` | Expand last token from most recent command |
613 | `!!:n-m` | Expand range of tokens from most recent command |
614 | `!!:n-$` | Expand `n`th token to last from most recent command |
616 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
622 ### Numeric calculations
625 $((a + 200)) # Add 200 to $a
629 $(($RANDOM%200)) # Random number 0..199
635 (cd somedir; echo "I'm now in $PWD")
636 pwd # still in first directory
642 python hello.py > output.txt # stdout to (file)
643 python hello.py >> output.txt # stdout to (file), append
644 python hello.py 2> error.log # stderr to (file)
645 python hello.py 2>&1 # stderr to stdout
646 python hello.py 2>/dev/null # stderr to (null)
647 python hello.py &>/dev/null # stdout and stderr to (null)
651 python hello.py < foo.txt # feed foo.txt to stdin for python
654 ### Inspecting commands
658 #=> "cd is a function/alias/whatever"
664 trap 'echo Error at about $LINENO' ERR
671 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
687 echo "Usage: $0 {start|stop|ssh}"
695 source "${0%/*}/../share/foo.sh"
701 printf "Hello %s, I'm %s" Sven Olga
702 #=> "Hello Sven, I'm Olga
704 printf "1 + 1 = %d" 2
707 printf "This is how you print a float: %f" 2
708 #=> "This is how you print a float: 2.000000"
711 ### Directory of script
720 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
732 if [[ "$1" == '--' ]]; then shift; fi
746 echo -n "Proceed? [y/n]: "
752 read -n 1 ans # Just one character
755 ### Special variables
757 | Expression | Description |
758 | ---------- | ---------------------------- |
759 | `$?` | Exit status of last task |
760 | `$!` | PID of last background task |
761 | `$$` | PID of shell |
762 | `$0` | Filename of the shell script |
764 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
766 ### Go to previous directory
771 pwd # /home/user/foo/bar
776 ### Check for command's result
779 if ping -c 1 google.com; then
780 echo "It appears you have a working internet connection"
787 if grep -q 'foo' ~/.bash_history; then
788 echo "You appear to have typed 'foo' in the past"
795 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
796 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
797 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
798 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
799 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_