13 - Conditional execution
14 - Command substitution
43 echo "Hi $NAME" #=> Hi John
44 echo 'Hi $NAME' #=> Hi $NAME
55 See [Command substitution](http://wiki.bash-hackers.org/syntax/expansion/cmdsubst)
57 ### Conditional execution
60 git commit && git push
61 git commit || echo "Commit failed"
65 {: id='functions-example'}
72 echo "You are $(get_name)"
75 See: [Functions](#functions)
78 {: id='conditionals-example'}
81 if [[ -z "$string" ]]; then
82 echo "String is empty"
83 elif [[ -n "$string" ]]; then
84 echo "String is not empty"
88 See: [Conditionals](#conditionals)
97 See: [Unofficial bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
105 | Expression | Description |
106 | ---------- | ------------------- |
107 | `{A,B}` | Same as `A B` |
108 | `{A,B}.js` | Same as `A.js B.js` |
109 | `{1..5}` | Same as `1 2 3 4 5` |
111 See: [Brace expansion](http://wiki.bash-hackers.org/syntax/expansion/brace)
123 echo ${name/J/j} #=> "john" (substitution)
124 echo ${name:0:2} #=> "Jo" (slicing)
125 echo ${name::2} #=> "Jo" (slicing)
126 echo ${name::-1} #=> "Joh" (slicing)
127 echo ${name:(-1)} #=> "n" (slicing from right)
128 echo ${name:(-2):1} #=> "h" (slicing from right)
129 echo ${food:-Cake} #=> $food or "Cake"
134 echo ${name:0:length} #=> "Jo"
137 See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
140 STR="/path/to/foo.cpp"
141 echo ${STR%.cpp} # /path/to/foo
142 echo ${STR%.cpp}.o # /path/to/foo.o
143 echo ${STR%/*} # /path/to
145 echo ${STR##*.} # cpp (extension)
146 echo ${STR##*/} # foo.cpp (basepath)
148 echo ${STR#*/} # path/to/foo.cpp
149 echo ${STR##*/} # foo.cpp
151 echo ${STR/foo/bar} # /path/to/bar.cpp
156 echo ${STR:6:5} # "world"
157 echo ${STR:-5:5} # "world"
161 SRC="/path/to/foo.cpp"
162 BASE=${SRC##*/} #=> "foo.cpp" (basepath)
163 DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
168 | Code | Description |
169 | ----------------- | ------------------- |
170 | `${FOO%suffix}` | Remove suffix |
171 | `${FOO#prefix}` | Remove prefix |
173 | `${FOO%%suffix}` | Remove long suffix |
174 | `${FOO##prefix}` | Remove long prefix |
176 | `${FOO/from/to}` | Replace first match |
177 | `${FOO//from/to}` | Replace all |
179 | `${FOO/%from/to}` | Replace suffix |
180 | `${FOO/#from/to}` | Replace prefix |
185 # Single line comment
198 | Expression | Description |
199 | --------------- | ------------------------------ |
200 | `${FOO:0:3}` | Substring _(position, length)_ |
201 | `${FOO:(-3):3}` | Substring from the right |
205 | Expression | Description |
206 | ---------- | ---------------- |
207 | `${#FOO}` | Length of `$FOO` |
213 echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
214 echo ${STR,,} #=> "hello world!" (all lowercase)
217 echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
218 echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
223 | Expression | Description |
224 | ----------------- | -------------------------------------------------------- |
225 | `${FOO:-val}` | `$FOO`, or `val` if unset (or null) |
226 | `${FOO:=val}` | Set `$FOO` to `val` if unset (or null) |
227 | `${FOO:+val}` | `val` if `$FOO` is set (and not null) |
228 | `${FOO:?message}` | Show error message and exit if `$FOO` is unset (or null) |
230 Omitting the `:` removes the (non)nullity checks, e.g. `${FOO-val}` expands to `val` if unset otherwise `$FOO`.
239 for i in /etc/rc.*; do
247 for ((i = 0 ; i < 100 ; i++)); do
263 for i in {5..50..5}; do
271 cat file.txt | while read line; do
288 ### Defining functions
297 # Same as above (alternate syntax)
311 local myresult='some value'
338 | Expression | Description |
340 | `$#` | Number of arguments |
341 | `$*` | All arguments |
342 | `$@` | All arguments, starting from first |
343 | `$1` | First argument |
344 | `$_` | Last argument of the previous command |
346 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
354 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.
356 | Condition | Description |
358 | `[[ -z STRING ]]` | Empty string |
359 | `[[ -n STRING ]]` | Not empty string |
360 | `[[ STRING == STRING ]]` | Equal |
361 | `[[ STRING != STRING ]]` | Not Equal |
363 | `[[ NUM -eq NUM ]]` | Equal |
364 | `[[ NUM -ne NUM ]]` | Not equal |
365 | `[[ NUM -lt NUM ]]` | Less than |
366 | `[[ NUM -le NUM ]]` | Less than or equal |
367 | `[[ NUM -gt NUM ]]` | Greater than |
368 | `[[ NUM -ge NUM ]]` | Greater than or equal |
370 | `[[ STRING =~ STRING ]]` | Regexp |
372 | `(( NUM < NUM ))` | Numeric conditions |
376 | Condition | Description |
377 | -------------------- | ------------------------ |
378 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
380 | `[[ ! EXPR ]]` | Not |
381 | `[[ X && Y ]]` | And |
382 | `[[ X || Y ]]` | Or |
386 | Condition | Description |
388 | `[[ -e FILE ]]` | Exists |
389 | `[[ -r FILE ]]` | Readable |
390 | `[[ -h FILE ]]` | Symlink |
391 | `[[ -d FILE ]]` | Directory |
392 | `[[ -w FILE ]]` | Writable |
393 | `[[ -s FILE ]]` | Size is > 0 bytes |
394 | `[[ -f FILE ]]` | File |
395 | `[[ -x FILE ]]` | Executable |
397 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
398 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
399 | `[[ FILE1 -ef FILE2 ]]` | Same files |
405 if [[ -z "$string" ]]; then
406 echo "String is empty"
407 elif [[ -n "$string" ]]; then
408 echo "String is not empty"
410 echo "This never happens"
416 if [[ X && Y ]]; then
423 if [[ "$A" == "$B" ]]
432 if (( $a < $b )); then
433 echo "$a is smaller than $b"
438 if [[ -e "file.txt" ]]; then
449 Fruits=('Apple' 'Banana' 'Orange')
458 ### Working with arrays
461 echo ${Fruits[0]} # Element #0
462 echo ${Fruits[-1]} # Last element
463 echo ${Fruits[@]} # All elements, space-separated
464 echo ${#Fruits[@]} # Number of elements
465 echo ${#Fruits} # String length of the 1st element
466 echo ${#Fruits[3]} # String length of the Nth element
467 echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
468 echo ${!Fruits[@]} # Keys of all elements, space-separated
474 Fruits=("${Fruits[@]}" "Watermelon") # Push
475 Fruits+=('Watermelon') # Also Push
476 Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
477 unset Fruits[2] # Remove one item
478 Fruits=("${Fruits[@]}") # Duplicate
479 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
480 lines=(`cat "logfile"`) # Read from file
486 for i in "${arrayName[@]}"; do
508 Declares `sound` as a Dictionary object (aka associative array).
510 ### Working with dictionaries
513 echo ${sounds[dog]} # Dog's sound
514 echo ${sounds[@]} # All values
515 echo ${!sounds[@]} # All keys
516 echo ${#sounds[@]} # Number of elements
517 unset sounds[dog] # Delete dog
522 #### Iterate over values
525 for val in "${sounds[@]}"; do
530 #### Iterate over keys
533 for key in "${!sounds[@]}"; do
544 set -o noclobber # Avoid overlay files (echo "hi" > foo)
545 set -o errexit # Used to exit upon error, avoiding cascading errors
546 set -o pipefail # Unveils hidden failures
547 set -o nounset # Exposes unset variables
553 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
554 shopt -s failglob # Non-matching globs throw errors
555 shopt -s nocaseglob # Case insensitive globs
556 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
557 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
560 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
568 | Command | Description |
569 | --------------------- | ----------------------------------------- |
570 | `history` | Show history |
571 | `shopt -s histverify` | Don't execute expanded result immediately |
575 | Expression | Description |
576 | ------------ | ---------------------------------------------------- |
577 | `!$` | Expand last parameter of most recent command |
578 | `!*` | Expand all parameters of most recent command |
579 | `!-n` | Expand `n`th most recent command |
580 | `!n` | Expand `n`th command in history |
581 | `!<command>` | Expand most recent invocation of command `<command>` |
585 | Code | Description |
586 | -------------------- | --------------------------------------------------------------------- |
587 | `!!` | Execute last command again |
588 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
589 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
590 | `!$:t` | Expand only basename from last parameter of most recent command |
591 | `!$:h` | Expand only directory from last parameter of most recent command |
593 `!!` and `!$` can be replaced with any valid expansion.
597 | Code | Description |
598 | -------- | ---------------------------------------------------------------------------------------- |
599 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
600 | `!^` | Expand first argument from most recent command |
601 | `!$` | Expand last token from most recent command |
602 | `!!:n-m` | Expand range of tokens from most recent command |
603 | `!!:n-$` | Expand `n`th token to last from most recent command |
605 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
611 ### Numeric calculations
614 $((a + 200)) # Add 200 to $a
618 $((RANDOM%=200)) # Random number 0..200
624 (cd somedir; echo "I'm now in $PWD")
625 pwd # still in first directory
631 python hello.py > output.txt # stdout to (file)
632 python hello.py >> output.txt # stdout to (file), append
633 python hello.py 2> error.log # stderr to (file)
634 python hello.py 2>&1 # stderr to stdout
635 python hello.py 2>/dev/null # stderr to (null)
636 python hello.py &>/dev/null # stdout and stderr to (null)
640 python hello.py < foo.txt # feed foo.txt to stdin for python
643 ### Inspecting commands
647 #=> "cd is a function/alias/whatever"
653 trap 'echo Error at about $LINENO' ERR
660 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
676 echo "Usage: $0 {start|stop|ssh}"
684 source "${0%/*}/../share/foo.sh"
690 printf "Hello %s, I'm %s" Sven Olga
691 #=> "Hello Sven, I'm Olga
693 printf "1 + 1 = %d" 2
696 printf "This is how you print a float: %f" 2
697 #=> "This is how you print a float: 2.000000"
700 ### Directory of script
709 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
721 if [[ "$1" == '--' ]]; then shift; fi
735 echo -n "Proceed? [y/n]: "
741 read -n 1 ans # Just one character
744 ### Special variables
746 | Expression | Description |
747 | ---------- | ---------------------------- |
748 | `$?` | Exit status of last task |
749 | `$!` | PID of last background task |
750 | `$$` | PID of shell |
751 | `$0` | Filename of the shell script |
753 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
755 ### Go to previous directory
760 pwd # /home/user/foo/bar
765 ### Check for command's result
768 if ping -c 1 google.com; then
769 echo "It appears you have a working internet connection"
776 if grep -q 'foo' ~/.bash_history; then
777 echo "You appear to have typed 'foo' in the past"
784 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
785 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
786 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
787 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
788 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_