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
142 echo ${STR##*.} # cpp (extension)
143 echo ${STR##*/} # foo.cpp (basepath)
145 echo ${STR#*/} # path/to/foo.cpp
146 echo ${STR##*/} # foo.cpp
148 echo ${STR/foo/bar} # /path/to/bar.cpp
153 echo ${STR:6:5} # "world"
154 echo ${STR:-5:5} # "world"
158 SRC="/path/to/foo.cpp"
159 BASE=${SRC##*/} #=> "foo.cpp" (basepath)
160 DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
165 | Code | Description |
167 | `${FOO%suffix}` | Remove suffix |
168 | `${FOO#prefix}` | Remove prefix |
170 | `${FOO%%suffix}` | Remove long suffix |
171 | `${FOO##prefix}` | Remove long prefix |
173 | `${FOO/from/to}` | Replace first match |
174 | `${FOO//from/to}` | Replace all |
176 | `${FOO/%from/to}` | Replace suffix |
177 | `${FOO/#from/to}` | Replace prefix |
182 # Single line comment
195 | `${FOO:0:3}` | Substring _(position, length)_ |
196 | `${FOO:-3:3}` | Substring from the right |
200 | `${#FOO}` | Length of `$FOO` |
206 echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
207 echo ${STR,,} #=> "hello world!" (all lowercase)
210 echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
211 echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
217 | `${FOO:-val}` | `$FOO`, or `val` if not set |
218 | `${FOO:=val}` | Set `$FOO` to `val` if not set |
219 | `${FOO:+val}` | `val` if `$FOO` is set |
220 | `${FOO:?message}` | Show error message and exit if `$FOO` is not set |
222 The `:` is optional (eg, `${FOO=word}` works)
231 for i in /etc/rc.*; do
239 for ((i = 0 ; i < 100 ; i++)); do
255 for i in {5..50..5}; do
263 < file.txt | while read line; do
280 ### Defining functions
289 # Same as above (alternate syntax)
303 local myresult='some value'
330 | Expression | Description |
332 | `$#` | Number of arguments |
333 | `$*` | All arguments |
334 | `$@` | All arguments, starting from first |
335 | `$1` | First argument |
337 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
345 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.
347 | Condition | Description |
349 | `[[ -z STRING ]]` | Empty string |
350 | `[[ -n STRING ]]` | Not empty string |
351 | `[[ STRING == STRING ]]` | Equal |
352 | `[[ STRING != STRING ]]` | Not Equal |
354 | `[[ NUM -eq NUM ]]` | Equal |
355 | `[[ NUM -ne NUM ]]` | Not equal |
356 | `[[ NUM -lt NUM ]]` | Less than |
357 | `[[ NUM -le NUM ]]` | Less than or equal |
358 | `[[ NUM -gt NUM ]]` | Greater than |
359 | `[[ NUM -ge NUM ]]` | Greater than or equal |
361 | `[[ STRING =~ STRING ]]` | Regexp |
363 | `(( NUM < NUM ))` | Numeric conditions |
365 | Condition | Description |
367 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
369 | `[[ ! EXPR ]]` | Not |
370 | `[[ X ]] && [[ Y ]]` | And |
371 | `[[ X ]] || [[ Y ]]` | Or |
375 | Condition | Description |
377 | `[[ -e FILE ]]` | Exists |
378 | `[[ -r FILE ]]` | Readable |
379 | `[[ -h FILE ]]` | Symlink |
380 | `[[ -d FILE ]]` | Directory |
381 | `[[ -w FILE ]]` | Writable |
382 | `[[ -s FILE ]]` | Size is > 0 bytes |
383 | `[[ -f FILE ]]` | File |
384 | `[[ -x FILE ]]` | Executable |
386 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
387 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
388 | `[[ FILE1 -ef FILE2 ]]` | Same files |
394 if [[ -z "$string" ]]; then
395 echo "String is empty"
396 elif [[ -n "$string" ]]; then
397 echo "String is not empty"
403 if [[ X ]] && [[ Y ]]; then
410 if [[ "$A" == "$B" ]]
419 if (( $a < $b )); then
420 echo "$a is smaller than $b"
425 if [[ -e "file.txt" ]]; then
436 Fruits=('Apple' 'Banana' 'Orange')
445 ### Working with arrays
448 echo ${Fruits[0]} # Element #0
449 echo ${Fruits[@]} # All elements, space-separated
450 echo ${#Fruits[@]} # Number of elements
451 echo ${#Fruits} # String length of the 1st element
452 echo ${#Fruits[3]} # String length of the Nth element
453 echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
459 Fruits=("${Fruits[@]}" "Watermelon") # Push
460 Fruits+=('Watermelon') # Also Push
461 Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
462 unset Fruits[2] # Remove one item
463 Fruits=("${Fruits[@]}") # Duplicate
464 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
465 lines=(`cat "logfile"`) # Read from file
471 for i in "${arrayName[@]}"; do
493 Declares `sound` as a Dictionary object (aka associative array).
495 ### Working with dictionaries
498 echo ${sounds[dog]} # Dog's sound
499 echo ${sounds[@]} # All values
500 echo ${!sounds[@]} # All keys
501 echo ${#sounds[@]} # Number of elements
502 unset sounds[dog] # Delete dog
507 #### Iterate over values
510 for val in "${sounds[@]}"; do
515 #### Iterate over keys
518 for key in "${!sounds[@]}"; do
529 set -o noclobber # Avoid overlay files (echo "hi" > foo)
530 set -o errexit # Used to exit upon error, avoiding cascading errors
531 set -o pipefail # Unveils hidden failures
532 set -o nounset # Exposes unset variables
538 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
539 shopt -s failglob # Non-matching globs throw errors
540 shopt -s nocaseglob # Case insensitive globs
541 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
542 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
545 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
553 | `history` | Show history |
554 | `shopt -s histverify` | Don't execute expanded result immediately |
558 | `!$` | Expand last parameter of most recent command |
559 | `!*` | Expand all parameters of most recent command |
560 | `!-n` | Expand `n`th most recent command |
561 | `!n` | Expand `n`th command in history |
562 | `!<command>` | Expand most recent invocation of command `<command>` |
566 | `!!` | Execute last command again |
567 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
568 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
569 | `!$:t` | Expand only basename from last parameter of most recent command |
570 | `!$:h` | Expand only directory from last parameter of most recent command |
572 `!!` and `!$` can be replaced with any valid expansion.
576 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
577 | `!^` | Expand first argument from most recent command |
578 | `!$` | Expand last token from most recent command |
579 | `!!:n-m` | Expand range of tokens from most recent command |
580 | `!!:n-$` | Expand `n`th token to last from most recent command |
582 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
588 ### Numeric calculations
591 $((a + 200)) # Add 200 to $a
595 $((RANDOM%=200)) # Random number 0..200
601 (cd somedir; echo "I'm now in $PWD")
602 pwd # still in first directory
608 python hello.py > output.txt # stdout to (file)
609 python hello.py >> output.txt # stdout to (file), append
610 python hello.py 2> error.log # stderr to (file)
611 python hello.py 2>&1 # stderr to stdout
612 python hello.py 2>/dev/null # stderr to (null)
613 python hello.py &>/dev/null # stdout and stderr to (null)
617 python hello.py < foo.txt # feed foo.txt to stdin for python
620 ### Inspecting commands
624 #=> "cd is a function/alias/whatever"
630 trap 'echo Error at about $LINENO' ERR
637 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
653 echo "Usage: $0 {start|stop|ssh}"
661 source "${0%/*}/../share/foo.sh"
667 printf "Hello %s, I'm %s" Sven Olga
668 #=> "Hello Sven, I'm Olga
670 printf "1 + 1 = %d" 2
673 printf "This is how you print a float: %f" 2
674 #=> "This is how you print a float: 2.000000"
677 ### Directory of script
686 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
698 if [[ "$1" == '--' ]]; then shift; fi
712 echo -n "Proceed? [y/n]: "
718 read -n 1 ans # Just one character
721 ### Special variables
723 | `$?` | Exit status of last task |
724 | `$!` | PID of last background task |
725 | `$$` | PID of shell |
726 | `$0` | Filename of the shell script |
728 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
730 ### Go to previous directory
735 pwd # /home/user/foo/bar
740 ### Check for command's result
743 if ping -c 1 google.com; then
744 echo "It appears you have a working internet connection"
751 if grep -q 'foo' ~/.bash_history; then
752 echo "You appear to have typed 'foo' in the past"
759 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
760 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
761 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
762 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
763 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_