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 | `{A,B}` | Same as `A B` |
106 | `{A,B}.js` | Same as `A.js B.js` |
107 | `{1..5}` | Same as `1 2 3 4 5` |
109 See: [Brace expansion](http://wiki.bash-hackers.org/syntax/expansion/brace)
121 echo ${name/J/j} #=> "john" (substitution)
122 echo ${name:0:2} #=> "Jo" (slicing)
123 echo ${name::2} #=> "Jo" (slicing)
124 echo ${name::-1} #=> "Joh" (slicing)
125 echo ${name:(-1)} #=> "n" (slicing from right)
126 echo ${name:(-2):1} #=> "h" (slicing from right)
127 echo ${food:-Cake} #=> $food or "Cake"
132 echo ${name:0:length} #=> "Jo"
135 See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
138 STR="/path/to/foo.cpp"
139 echo ${STR%.cpp} # /path/to/foo
140 echo ${STR%.cpp}.o # /path/to/foo.o
141 echo ${STR%/*} # /path/to
143 echo ${STR##*.} # cpp (extension)
144 echo ${STR##*/} # foo.cpp (basepath)
146 echo ${STR#*/} # path/to/foo.cpp
147 echo ${STR##*/} # foo.cpp
149 echo ${STR/foo/bar} # /path/to/bar.cpp
154 echo ${STR:6:5} # "world"
155 echo ${STR:-5:5} # "world"
159 SRC="/path/to/foo.cpp"
160 BASE=${SRC##*/} #=> "foo.cpp" (basepath)
161 DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
166 | Code | Description |
168 | `${FOO%suffix}` | Remove suffix |
169 | `${FOO#prefix}` | Remove prefix |
171 | `${FOO%%suffix}` | Remove long suffix |
172 | `${FOO##prefix}` | Remove long prefix |
174 | `${FOO/from/to}` | Replace first match |
175 | `${FOO//from/to}` | Replace all |
177 | `${FOO/%from/to}` | Replace suffix |
178 | `${FOO/#from/to}` | Replace prefix |
183 # Single line comment
196 | Expression | Description |
197 | --------------- | ------------------------------ |
198 | `${FOO:0:3}` | Substring _(position, length)_ |
199 | `${FOO:(-3):3}` | Substring from the right |
203 | Expression | Description |
204 | ---------- | ---------------- |
205 | `${#FOO}` | Length of `$FOO` |
211 echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
212 echo ${STR,,} #=> "hello world!" (all lowercase)
215 echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
216 echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
221 | Expression | Description |
222 | ----------------- | -------------------------------------------------------- |
223 | `${FOO:-val}` | `$FOO`, or `val` if unset (or null) |
224 | `${FOO:=val}` | Set `$FOO` to `val` if unset (or null) |
225 | `${FOO:+val}` | `val` if `$FOO` is set (and not null) |
226 | `${FOO:?message}` | Show error message and exit if `$FOO` is unset (or null) |
228 Omitting the `:` removes the (non)nullity checks, e.g. `${FOO-val}` expands to `val` if unset otherwise `$FOO`.
237 for i in /etc/rc.*; do
245 for ((i = 0 ; i < 100 ; i++)); do
261 for i in {5..50..5}; do
269 cat file.txt | while read line; do
286 ### Defining functions
295 # Same as above (alternate syntax)
309 local myresult='some value'
336 | Expression | Description |
338 | `$#` | Number of arguments |
339 | `$*` | All arguments |
340 | `$@` | All arguments, starting from first |
341 | `$1` | First argument |
342 | `$_` | Last argument of the previous command |
344 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
352 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.
354 | Condition | Description |
356 | `[[ -z STRING ]]` | Empty string |
357 | `[[ -n STRING ]]` | Not empty string |
358 | `[[ STRING == STRING ]]` | Equal |
359 | `[[ STRING != STRING ]]` | Not Equal |
361 | `[[ NUM -eq NUM ]]` | Equal |
362 | `[[ NUM -ne NUM ]]` | Not equal |
363 | `[[ NUM -lt NUM ]]` | Less than |
364 | `[[ NUM -le NUM ]]` | Less than or equal |
365 | `[[ NUM -gt NUM ]]` | Greater than |
366 | `[[ NUM -ge NUM ]]` | Greater than or equal |
368 | `[[ STRING =~ STRING ]]` | Regexp |
370 | `(( NUM < NUM ))` | Numeric conditions |
374 | Condition | Description |
375 | -------------------- | ------------------------ |
376 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
378 | `[[ ! EXPR ]]` | Not |
379 | `[[ X && Y ]]` | And |
380 | `[[ X || Y ]]` | Or |
384 | Condition | Description |
386 | `[[ -e FILE ]]` | Exists |
387 | `[[ -r FILE ]]` | Readable |
388 | `[[ -h FILE ]]` | Symlink |
389 | `[[ -d FILE ]]` | Directory |
390 | `[[ -w FILE ]]` | Writable |
391 | `[[ -s FILE ]]` | Size is > 0 bytes |
392 | `[[ -f FILE ]]` | File |
393 | `[[ -x FILE ]]` | Executable |
395 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
396 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
397 | `[[ FILE1 -ef FILE2 ]]` | Same files |
403 if [[ -z "$string" ]]; then
404 echo "String is empty"
405 elif [[ -n "$string" ]]; then
406 echo "String is not empty"
412 if [[ X && Y ]]; then
419 if [[ "$A" == "$B" ]]
428 if (( $a < $b )); then
429 echo "$a is smaller than $b"
434 if [[ -e "file.txt" ]]; then
445 Fruits=('Apple' 'Banana' 'Orange')
454 ### Working with arrays
457 echo ${Fruits[0]} # Element #0
458 echo ${Fruits[-1]} # Last element
459 echo ${Fruits[@]} # All elements, space-separated
460 echo ${#Fruits[@]} # Number of elements
461 echo ${#Fruits} # String length of the 1st element
462 echo ${#Fruits[3]} # String length of the Nth element
463 echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
464 echo ${!Fruits[@]} # Keys of all elements, space-separated
470 Fruits=("${Fruits[@]}" "Watermelon") # Push
471 Fruits+=('Watermelon') # Also Push
472 Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
473 unset Fruits[2] # Remove one item
474 Fruits=("${Fruits[@]}") # Duplicate
475 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
476 lines=(`cat "logfile"`) # Read from file
482 for i in "${arrayName[@]}"; do
504 Declares `sound` as a Dictionary object (aka associative array).
506 ### Working with dictionaries
509 echo ${sounds[dog]} # Dog's sound
510 echo ${sounds[@]} # All values
511 echo ${!sounds[@]} # All keys
512 echo ${#sounds[@]} # Number of elements
513 unset sounds[dog] # Delete dog
518 #### Iterate over values
521 for val in "${sounds[@]}"; do
526 #### Iterate over keys
529 for key in "${!sounds[@]}"; do
540 set -o noclobber # Avoid overlay files (echo "hi" > foo)
541 set -o errexit # Used to exit upon error, avoiding cascading errors
542 set -o pipefail # Unveils hidden failures
543 set -o nounset # Exposes unset variables
549 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
550 shopt -s failglob # Non-matching globs throw errors
551 shopt -s nocaseglob # Case insensitive globs
552 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
553 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
556 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
564 | `history` | Show history |
565 | `shopt -s histverify` | Don't execute expanded result immediately |
569 | `!$` | Expand last parameter of most recent command |
570 | `!*` | Expand all parameters of most recent command |
571 | `!-n` | Expand `n`th most recent command |
572 | `!n` | Expand `n`th command in history |
573 | `!<command>` | Expand most recent invocation of command `<command>` |
577 | Code | Description |
578 | -------------------- | --------------------------------------------------------------------- |
579 | `!!` | Execute last command again |
580 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
581 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
582 | `!$:t` | Expand only basename from last parameter of most recent command |
583 | `!$:h` | Expand only directory from last parameter of most recent command |
585 `!!` and `!$` can be replaced with any valid expansion.
589 | Code | Description |
590 | -------- | ---------------------------------------------------------------------------------------- |
591 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
592 | `!^` | Expand first argument from most recent command |
593 | `!$` | Expand last token from most recent command |
594 | `!!:n-m` | Expand range of tokens from most recent command |
595 | `!!:n-$` | Expand `n`th token to last from most recent command |
597 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
603 ### Numeric calculations
606 $((a + 200)) # Add 200 to $a
610 $((RANDOM%=200)) # Random number 0..200
616 (cd somedir; echo "I'm now in $PWD")
617 pwd # still in first directory
623 python hello.py > output.txt # stdout to (file)
624 python hello.py >> output.txt # stdout to (file), append
625 python hello.py 2> error.log # stderr to (file)
626 python hello.py 2>&1 # stderr to stdout
627 python hello.py 2>/dev/null # stderr to (null)
628 python hello.py &>/dev/null # stdout and stderr to (null)
632 python hello.py < foo.txt # feed foo.txt to stdin for python
635 ### Inspecting commands
639 #=> "cd is a function/alias/whatever"
645 trap 'echo Error at about $LINENO' ERR
652 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
668 echo "Usage: $0 {start|stop|ssh}"
676 source "${0%/*}/../share/foo.sh"
682 printf "Hello %s, I'm %s" Sven Olga
683 #=> "Hello Sven, I'm Olga
685 printf "1 + 1 = %d" 2
688 printf "This is how you print a float: %f" 2
689 #=> "This is how you print a float: 2.000000"
692 ### Directory of script
701 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
713 if [[ "$1" == '--' ]]; then shift; fi
727 echo -n "Proceed? [y/n]: "
733 read -n 1 ans # Just one character
736 ### Special variables
738 | `$?` | Exit status of last task |
739 | `$!` | PID of last background task |
740 | `$$` | PID of shell |
741 | `$0` | Filename of the shell script |
743 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
745 ### Go to previous directory
750 pwd # /home/user/foo/bar
755 ### Check for command's result
758 if ping -c 1 google.com; then
759 echo "It appears you have a working internet connection"
766 if grep -q 'foo' ~/.bash_history; then
767 echo "You appear to have typed 'foo' in the past"
774 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
775 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
776 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
777 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
778 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_