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` |
204 | `${FOO:-val}` | `$FOO`, or `val` if not set |
205 | `${FOO:=val}` | Set `$FOO` to `val` if not set |
206 | `${FOO:+val}` | `val` if `$FOO` is set |
207 | `${FOO:?message}` | Show error message and exit if `$FOO` is not set |
209 The `:` is optional (eg, `${FOO=word}` works)
218 for i in /etc/rc.*; do
226 for ((i = 0 ; i < 100 ; i++)); do
242 for i in {5..50..5}; do
250 < file.txt | while read line; do
267 ### Defining functions
276 # Same as above (alternate syntax)
290 local myresult='some value'
317 | Expression | Description |
319 | `$#` | Number of arguments |
320 | `$*` | All arguments |
321 | `$@` | All arguments, starting from first |
322 | `$1` | First argument |
324 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
332 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.
334 | Condition | Description |
336 | `[[ -z STRING ]]` | Empty string |
337 | `[[ -n STRING ]]` | Not empty string |
338 | `[[ STRING == STRING ]]` | Equal |
339 | `[[ STRING != STRING ]]` | Not Equal |
341 | `[[ NUM -eq NUM ]]` | Equal |
342 | `[[ NUM -ne NUM ]]` | Not equal |
343 | `[[ NUM -lt NUM ]]` | Less than |
344 | `[[ NUM -le NUM ]]` | Less than or equal |
345 | `[[ NUM -gt NUM ]]` | Greater than |
346 | `[[ NUM -ge NUM ]]` | Greater than or equal |
348 | `[[ STRING =~ STRING ]]` | Regexp |
350 | `(( NUM < NUM ))` | Numeric conditions |
352 | Condition | Description |
354 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
356 | `[[ ! EXPR ]]` | Not |
357 | `[[ X ]] && [[ Y ]]` | And |
358 | `[[ X ]] || [[ Y ]]` | Or |
362 | Condition | Description |
364 | `[[ -e FILE ]]` | Exists |
365 | `[[ -r FILE ]]` | Readable |
366 | `[[ -h FILE ]]` | Symlink |
367 | `[[ -d FILE ]]` | Directory |
368 | `[[ -w FILE ]]` | Writable |
369 | `[[ -s FILE ]]` | Size is > 0 bytes |
370 | `[[ -f FILE ]]` | File |
371 | `[[ -x FILE ]]` | Executable |
373 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
374 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
375 | `[[ FILE1 -ef FILE2 ]]` | Same files |
380 if ping -c 1 google.com; then
381 echo "It appears you have a working internet connection"
386 if grep -q 'foo' ~/.bash_history; then
387 echo "You appear to have typed 'foo' in the past"
393 if [[ -z "$string" ]]; then
394 echo "String is empty"
395 elif [[ -n "$string" ]]; then
396 echo "String is not empty"
402 if [[ X ]] && [[ Y ]]; then
409 if [[ "$A" == "$B" ]]
418 if (( $a < $b )); then
419 echo "$a is smaller than $b"
424 if [[ -e "file.txt" ]]; then
435 Fruits=('Apple' 'Banana' 'Orange')
444 ### Working with arrays
447 echo ${Fruits[0]} # Element #0
448 echo ${Fruits[@]} # All elements, space-separated
449 echo ${#Fruits[@]} # Number of elements
450 echo ${#Fruits} # String length of the 1st element
451 echo ${#Fruits[3]} # String length of the Nth element
452 echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
458 Fruits=("${Fruits[@]}" "Watermelon") # Push
459 Fruits+=('Watermelon') # Also Push
460 Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
461 unset Fruits[2] # Remove one item
462 Fruits=("${Fruits[@]}") # Duplicate
463 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
464 lines=(`cat "logfile"`) # Read from file
470 for i in "${arrayName[@]}"; do
492 Declares `sound` as a Dictionary object (aka associative array).
494 ### Working with dictionaries
497 echo ${sounds[dog]} # Dog's sound
498 echo ${sounds[@]} # All values
499 echo ${!sounds[@]} # All keys
500 echo ${#sounds[@]} # Number of elements
501 unset sounds[dog] # Delete dog
506 #### Iterate over values
509 for val in "${sounds[@]}"; do
514 #### Iterate over keys
517 for key in "${!sounds[@]}"; do
528 set -o noclobber # Avoid overlay files (echo "hi" > foo)
529 set -o errexit # Used to exit upon error, avoiding cascading errors
530 set -o pipefail # Unveils hidden failures
531 set -o nounset # Exposes unset variables
537 set -o nullglob # Non-matching globs are removed ('*.foo' => '')
538 set -o failglob # Non-matching globs throw errors
539 set -o nocaseglob # Case insensitive globs
540 set -o globdots # Wildcards match dotfiles ("*.sh" => ".foo.sh")
541 set -o globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
544 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
552 | `history` | Show history |
553 | `shopt -s histverify` | Don't execute expanded result immediately |
557 | `!$` | Expand last parameter of most recent command |
558 | `!*` | Expand all parameters of most recent command |
559 | `!-n` | Expand `n`th most recent command |
560 | `!n` | Expand `n`th command in history |
561 | `!<command>` | Expand most recent invocation of command `<command>` |
565 | `!!` | Execute last command again |
566 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
567 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
568 | `!$:t` | Expand only basename from last parameter of most recent command |
569 | `!$:h` | Expand only directory from last parameter of most recent command |
571 `!!` and `!$` can be replaced with any valid expansion.
575 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
576 | `!^` | Expand first argument from most recent command |
577 | `!$` | Expand last token from most recent command |
578 | `!!:n-m` | Expand range of tokens from most recent command |
579 | `!!:n-$` | Expand `n`th token to last from most recent command |
581 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
587 ### Numeric calculations
590 $((a + 200)) # Add 200 to $a
594 $((RANDOM%=200)) # Random number 0..200
600 (cd somedir; echo "I'm now in $PWD")
601 pwd # still in first directory
607 python hello.py > output.txt # stdout to (file)
608 python hello.py >> output.txt # stdout to (file), append
609 python hello.py 2> error.log # stderr to (file)
610 python hello.py 2>&1 # stderr to stdout
611 python hello.py 2>/dev/null # stderr to (null)
612 python hello.py &>/dev/null # stdout and stderr to (null)
616 python hello.py < foo.txt # feed foo.txt to stdin for python
619 ### Inspecting commands
623 #=> "cd is a function/alias/whatever"
629 trap 'echo Error at about $LINENO' ERR
636 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
652 echo "Usage: $0 {start|stop|ssh}"
660 source "${0%/*}/../share/foo.sh"
666 printf "Hello %s, I'm %s" Sven Olga
667 #=> "Hello Sven, I'm Olga
670 ### Directory of script
679 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
691 if [[ "$1" == '--' ]]; then shift; fi
705 echo -n "Proceed? [y/n]: "
711 read -n 1 ans # Just one character
714 ### Special variables
716 | `$?` | Exit status of last task |
717 | `$!` | PID of last background task |
718 | `$$` | PID of shell |
720 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
722 ### Go to previous directory
727 pwd # /home/user/foo/bar
735 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
736 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
737 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
738 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
739 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_