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)_
28 - [Bash Hackers Wiki](https://wiki.bash-hackers.org) _(wiki.bash-hackers.org)_
43 echo $name # see below
47 Generally quote your variables unless they contain wildcards to expand or command fragments.
52 cp -$options $wildcard /tmp
59 echo "Hi $name" #=> Hi John
60 echo 'Hi $name' #=> Hi $name
67 echo "I'm in `pwd`" # obsolescent
71 See [Command substitution](http://wiki.bash-hackers.org/syntax/expansion/cmdsubst)
73 ### Conditional execution
76 git commit && git push
77 git commit || echo "Commit failed"
81 {: id='functions-example'}
88 echo "You are $(get_name)"
91 See: [Functions](#functions)
94 {: id='conditionals-example'}
97 if [[ -z "$string" ]]; then
98 echo "String is empty"
99 elif [[ -n "$string" ]]; then
100 echo "String is not empty"
104 See: [Conditionals](#conditionals)
113 See: [Unofficial bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
121 | Expression | Description |
122 | ---------- | ------------------- |
123 | `{A,B}` | Same as `A B` |
124 | `{A,B}.js` | Same as `A.js B.js` |
125 | `{1..5}` | Same as `1 2 3 4 5` |
127 See: [Brace expansion](http://wiki.bash-hackers.org/syntax/expansion/brace)
139 echo "${name/J/j}" #=> "john" (substitution)
140 echo "${name:0:2}" #=> "Jo" (slicing)
141 echo "${name::2}" #=> "Jo" (slicing)
142 echo "${name::-1}" #=> "Joh" (slicing)
143 echo "${name:(-1)}" #=> "n" (slicing from right)
144 echo "${name:(-2):1}" #=> "h" (slicing from right)
145 echo "${food:-Cake}" #=> $food or "Cake"
150 echo "${name:0:length}" #=> "Jo"
153 See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
156 str="/path/to/foo.cpp"
157 echo "${str%.cpp}" # /path/to/foo
158 echo "${str%.cpp}.o" # /path/to/foo.o
159 echo "${str%/*}" # /path/to
161 echo "${str##*.}" # cpp (extension)
162 echo "${str##*/}" # foo.cpp (basepath)
164 echo "${str#*/}" # path/to/foo.cpp
165 echo "${str##*/}" # foo.cpp
167 echo "${str/foo/bar}" # /path/to/bar.cpp
172 echo "${str:6:5}" # "world"
173 echo "${str: -5:5}" # "world"
177 src="/path/to/foo.cpp"
178 base=${src##*/} #=> "foo.cpp" (basepath)
179 dir=${src%$base} #=> "/path/to/" (dirpath)
184 | Code | Description |
185 | ----------------- | ------------------- |
186 | `${foo%suffix}` | Remove suffix |
187 | `${foo#prefix}` | Remove prefix |
189 | `${foo%%suffix}` | Remove long suffix |
190 | `${foo/%suffix}` | Remove long suffix |
191 | `${foo##prefix}` | Remove long prefix |
192 | `${foo/#prefix}` | Remove long prefix |
194 | `${foo/from/to}` | Replace first match |
195 | `${foo//from/to}` | Replace all |
197 | `${foo/%from/to}` | Replace suffix |
198 | `${foo/#from/to}` | Replace prefix |
203 # Single line comment
216 | Expression | Description |
217 | --------------- | ------------------------------ |
218 | `${foo:0:3}` | Substring _(position, length)_ |
219 | `${foo:(-3):3}` | Substring from the right |
223 | Expression | Description |
224 | ---------- | ---------------- |
225 | `${#foo}` | Length of `$foo` |
231 echo "${str,}" #=> "hELLO WORLD!" (lowercase 1st letter)
232 echo "${str,,}" #=> "hello world!" (all lowercase)
235 echo "${str^}" #=> "Hello world!" (uppercase 1st letter)
236 echo "${str^^}" #=> "HELLO WORLD!" (all uppercase)
241 | Expression | Description |
242 | ----------------- | -------------------------------------------------------- |
243 | `${foo:-val}` | `$foo`, or `val` if unset (or null) |
244 | `${foo:=val}` | Set `$foo` to `val` if unset (or null) |
245 | `${foo:+val}` | `val` if `$foo` is set (and not null) |
246 | `${foo:?message}` | Show error message and exit if `$foo` is unset (or null) |
248 Omitting the `:` removes the (non)nullity checks, e.g. `${foo-val}` expands to `val` if unset otherwise `$foo`.
257 for i in /etc/rc.*; do
265 for ((i = 0 ; i < 100 ; i++)); do
281 for i in {5..50..5}; do
289 while read -r line; do
306 ### Defining functions
315 # Same as above (alternate syntax)
329 local myresult='some value'
356 | Expression | Description |
358 | `$#` | Number of arguments |
359 | `$*` | All positional arguments (as a single word) |
360 | `$@` | All positional arguments (as separate strings) |
361 | `$1` | First argument |
362 | `$_` | Last argument of the previous command |
364 **Note**: `$@` and `$*` must be quoted in order to perform as described.
365 Otherwise, they do exactly the same thing (arguments as separate strings).
367 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
375 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.
377 | Condition | Description |
379 | `[[ -z STRING ]]` | Empty string |
380 | `[[ -n STRING ]]` | Not empty string |
381 | `[[ STRING == STRING ]]` | Equal |
382 | `[[ STRING != STRING ]]` | Not Equal |
384 | `[[ NUM -eq NUM ]]` | Equal |
385 | `[[ NUM -ne NUM ]]` | Not equal |
386 | `[[ NUM -lt NUM ]]` | Less than |
387 | `[[ NUM -le NUM ]]` | Less than or equal |
388 | `[[ NUM -gt NUM ]]` | Greater than |
389 | `[[ NUM -ge NUM ]]` | Greater than or equal |
391 | `[[ STRING =~ STRING ]]` | Regexp |
393 | `(( NUM < NUM ))` | Numeric conditions |
397 | Condition | Description |
398 | -------------------- | ------------------------ |
399 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
401 | `[[ ! EXPR ]]` | Not |
402 | `[[ X && Y ]]` | And |
403 | `[[ X || Y ]]` | Or |
407 | Condition | Description |
409 | `[[ -e FILE ]]` | Exists |
410 | `[[ -r FILE ]]` | Readable |
411 | `[[ -h FILE ]]` | Symlink |
412 | `[[ -d FILE ]]` | Directory |
413 | `[[ -w FILE ]]` | Writable |
414 | `[[ -s FILE ]]` | Size is > 0 bytes |
415 | `[[ -f FILE ]]` | File |
416 | `[[ -x FILE ]]` | Executable |
418 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
419 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
420 | `[[ FILE1 -ef FILE2 ]]` | Same files |
426 if [[ -z "$string" ]]; then
427 echo "String is empty"
428 elif [[ -n "$string" ]]; then
429 echo "String is not empty"
431 echo "This never happens"
437 if [[ X && Y ]]; then
444 if [[ "$A" == "$B" ]]
453 if (( $a < $b )); then
454 echo "$a is smaller than $b"
459 if [[ -e "file.txt" ]]; then
470 Fruits=('Apple' 'Banana' 'Orange')
479 ### Working with arrays
482 echo "${Fruits[0]}" # Element #0
483 echo "${Fruits[-1]}" # Last element
484 echo "${Fruits[@]}" # All elements, space-separated
485 echo "${#Fruits[@]}" # Number of elements
486 echo "${#Fruits}" # String length of the 1st element
487 echo "${#Fruits[3]}" # String length of the Nth element
488 echo "${Fruits[@]:3:2}" # Range (from position 3, length 2)
489 echo "${!Fruits[@]}" # Keys of all elements, space-separated
495 Fruits=("${Fruits[@]}" "Watermelon") # Push
496 Fruits+=('Watermelon') # Also Push
497 Fruits=( "${Fruits[@]/Ap*/}" ) # Remove by regex match
498 unset Fruits[2] # Remove one item
499 Fruits=("${Fruits[@]}") # Duplicate
500 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
501 lines=(`cat "logfile"`) # Read from file
507 for i in "${arrayName[@]}"; do
529 Declares `sound` as a Dictionary object (aka associative array).
531 ### Working with dictionaries
534 echo "${sounds[dog]}" # Dog's sound
535 echo "${sounds[@]}" # All values
536 echo "${!sounds[@]}" # All keys
537 echo "${#sounds[@]}" # Number of elements
538 unset sounds[dog] # Delete dog
543 #### Iterate over values
546 for val in "${sounds[@]}"; do
551 #### Iterate over keys
554 for key in "${!sounds[@]}"; do
565 set -o noclobber # Avoid overlay files (echo "hi" > foo)
566 set -o errexit # Used to exit upon error, avoiding cascading errors
567 set -o pipefail # Unveils hidden failures
568 set -o nounset # Exposes unset variables
574 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
575 shopt -s failglob # Non-matching globs throw errors
576 shopt -s nocaseglob # Case insensitive globs
577 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
578 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
581 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
589 | Command | Description |
590 | --------------------- | ----------------------------------------- |
591 | `history` | Show history |
592 | `shopt -s histverify` | Don't execute expanded result immediately |
596 | Expression | Description |
597 | ------------ | ---------------------------------------------------- |
598 | `!$` | Expand last parameter of most recent command |
599 | `!*` | Expand all parameters of most recent command |
600 | `!-n` | Expand `n`th most recent command |
601 | `!n` | Expand `n`th command in history |
602 | `!<command>` | Expand most recent invocation of command `<command>` |
606 | Code | Description |
607 | -------------------- | --------------------------------------------------------------------- |
608 | `!!` | Execute last command again |
609 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
610 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
611 | `!$:t` | Expand only basename from last parameter of most recent command |
612 | `!$:h` | Expand only directory from last parameter of most recent command |
614 `!!` and `!$` can be replaced with any valid expansion.
618 | Code | Description |
619 | -------- | ---------------------------------------------------------------------------------------- |
620 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
621 | `!^` | Expand first argument from most recent command |
622 | `!$` | Expand last token from most recent command |
623 | `!!:n-m` | Expand range of tokens from most recent command |
624 | `!!:n-$` | Expand `n`th token to last from most recent command |
626 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
632 ### Numeric calculations
635 $((a + 200)) # Add 200 to $a
639 $(($RANDOM%200)) # Random number 0..199
643 declare -i count # Declare as type integer
650 (cd somedir; echo "I'm now in $PWD")
651 pwd # still in first directory
657 python hello.py > output.txt # stdout to (file)
658 python hello.py >> output.txt # stdout to (file), append
659 python hello.py 2> error.log # stderr to (file)
660 python hello.py 2>&1 # stderr to stdout
661 python hello.py 2>/dev/null # stderr to (null)
662 python hello.py >output.txt 2>&1 # stdout and stderr to (file), equivalent to &>
663 python hello.py &>/dev/null # stdout and stderr to (null)
664 echo "$0: warning: too many users" >&2 # print diagnostic message to stderr
668 python hello.py < foo.txt # feed foo.txt to stdin for python
669 diff <(ls -r) <(ls) # Compare two stdout without files
672 ### Inspecting commands
676 #=> "cd is a function/alias/whatever"
682 trap 'echo Error at about $LINENO' ERR
689 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
705 echo "Usage: $0 {start|stop|ssh}"
713 source "${0%/*}/../share/foo.sh"
719 printf "Hello %s, I'm %s" Sven Olga
720 #=> "Hello Sven, I'm Olga
722 printf "1 + 1 = %d" 2
725 printf "This is how you print a float: %f" 2
726 #=> "This is how you print a float: 2.000000"
728 printf '%s\n' '#!/bin/bash' 'echo hello' >file
729 # format string is applied to each group of arguments
730 printf '%i+%i=%i\n' 1 2 3 4 5 9
733 ### Transform strings
735 | Command option | Description |
736 | ------------------ | --------------------------------------------------- |
737 | `-c` | Operations apply to characters not in the given set |
738 | `-d` | Delete characters |
739 | `-s` | Replaces repeated characters with single occurrence |
741 | `[:upper:]` | All upper case letters |
742 | `[:lower:]` | All lower case letters |
743 | `[:digit:]` | All digits |
744 | `[:space:]` | All whitespace |
745 | `[:alpha:]` | All letters |
746 | `[:alnum:]` | All letters and digits |
751 echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]'
755 ### Directory of script
764 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
776 if [[ "$1" == '--' ]]; then shift; fi
790 echo -n "Proceed? [y/n]: "
795 The `-r` option disables a peculiar legacy behavior with backslashes.
798 read -n 1 ans # Just one character
801 ### Special variables
803 | Expression | Description |
804 | ------------------ | -------------------------------------- |
805 | `$?` | Exit status of last task |
806 | `$!` | PID of last background task |
807 | `$$` | PID of shell |
808 | `$0` | Filename of the shell script |
809 | `$_` | Last argument of the previous command |
810 | `${PIPESTATUS[n]}` | return value of piped commands (array) |
812 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
814 ### Go to previous directory
819 pwd # /home/user/foo/bar
824 ### Check for command's result
827 if ping -c 1 google.com; then
828 echo "It appears you have a working internet connection"
835 if grep -q 'foo' ~/.bash_history; then
836 echo "You appear to have typed 'foo' in the past"
843 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
844 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
845 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
846 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
847 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_