13 - Conditional execution
14 - Command substitution
25 This is a quick reference to getting started with Bash scripting.
27 - [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
28 - [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
29 - [Bash Hackers Wiki](https://web.archive.org/web/20230406205817/https://wiki.bash-hackers.org/) _(wiki.bash-hackers.org)_
44 echo $name # see below
49 Generally quote your variables unless they contain wildcards to expand or command fragments.
54 cp -$options $wildcard /tmp
61 echo "Hi $name" #=> Hi John
62 echo 'Hi $name' #=> Hi $name
69 echo "I'm in `pwd`" # obsolescent
73 See [Command substitution](https://web.archive.org/web/20230326081741/https://wiki.bash-hackers.org/syntax/expansion/cmdsubst)
75 ### Conditional execution
78 git commit && git push
79 git commit || echo "Commit failed"
84 {: id='functions-example'}
91 echo "You are $(get_name)"
94 See: [Functions](#functions)
98 {: id='conditionals-example'}
101 if [[ -z "$string" ]]; then
102 echo "String is empty"
103 elif [[ -n "$string" ]]; then
104 echo "String is not empty"
108 See: [Conditionals](#conditionals)
117 See: [Unofficial bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
125 | Expression | Description |
126 | ---------------------- | --------------------- |
127 | `{A,B}` | Same as `A B` |
128 | `{A,B}.js` | Same as `A.js B.js` |
129 | `{1..5}` | Same as `1 2 3 4 5` |
130 | <code>{{1..3},{7..9}}</code> | Same as `1 2 3 7 8 9` |
132 See: [Brace expansion](https://web.archive.org/web/20230207192110/https://wiki.bash-hackers.org/syntax/expansion/brace)
134 ## Parameter expansions
143 echo "${name/J/j}" #=> "john" (substitution)
144 echo "${name:0:2}" #=> "Jo" (slicing)
145 echo "${name::2}" #=> "Jo" (slicing)
146 echo "${name::-1}" #=> "Joh" (slicing)
147 echo "${name:(-1)}" #=> "n" (slicing from right)
148 echo "${name:(-2):1}" #=> "h" (slicing from right)
149 echo "${food:-Cake}" #=> $food or "Cake"
154 echo "${name:0:length}" #=> "Jo"
157 See: [Parameter expansion](https://web.archive.org/web/20230408142504/https://wiki.bash-hackers.org/syntax/pe)
160 str="/path/to/foo.cpp"
161 echo "${str%.cpp}" # /path/to/foo
162 echo "${str%.cpp}.o" # /path/to/foo.o
163 echo "${str%/*}" # /path/to
165 echo "${str##*.}" # cpp (extension)
166 echo "${str##*/}" # foo.cpp (basepath)
168 echo "${str#*/}" # path/to/foo.cpp
169 echo "${str##*/}" # foo.cpp
171 echo "${str/foo/bar}" # /path/to/bar.cpp
176 echo "${str:6:5}" # "world"
177 echo "${str: -5:5}" # "world"
181 src="/path/to/foo.cpp"
182 base=${src##*/} #=> "foo.cpp" (basepath)
183 dir=${src%$base} #=> "/path/to/" (dirpath)
188 | Code | Description |
189 | ----------------- | ------------------- |
190 | `${foo%suffix}` | Remove suffix |
191 | `${foo#prefix}` | Remove prefix |
193 | `${foo%%suffix}` | Remove long suffix |
194 | `${foo/%suffix}` | Remove long suffix |
195 | `${foo##prefix}` | Remove long prefix |
196 | `${foo/#prefix}` | Remove long prefix |
198 | `${foo/from/to}` | Replace first match |
199 | `${foo//from/to}` | Replace all |
201 | `${foo/%from/to}` | Replace suffix |
202 | `${foo/#from/to}` | Replace prefix |
207 # Single line comment
220 | Expression | Description |
221 | --------------- | ------------------------------ |
222 | `${foo:0:3}` | Substring _(position, length)_ |
223 | `${foo:(-3):3}` | Substring from the right |
227 | Expression | Description |
228 | ---------- | ---------------- |
229 | `${#foo}` | Length of `$foo` |
235 echo "${str,}" #=> "hELLO WORLD!" (lowercase 1st letter)
236 echo "${str,,}" #=> "hello world!" (all lowercase)
239 echo "${str^}" #=> "Hello world!" (uppercase 1st letter)
240 echo "${str^^}" #=> "HELLO WORLD!" (all uppercase)
245 | Expression | Description |
246 | ----------------- | -------------------------------------------------------- |
247 | `${foo:-val}` | `$foo`, or `val` if unset (or null) |
248 | `${foo:=val}` | Set `$foo` to `val` if unset (or null) |
249 | `${foo:+val}` | `val` if `$foo` is set (and not null) |
250 | `${foo:?message}` | Show error message and exit if `$foo` is unset (or null) |
252 Omitting the `:` removes the (non)nullity checks, e.g. `${foo-val}` expands to `val` if unset otherwise `$foo`.
261 for i in /etc/rc.*; do
269 for ((i = 0 ; i < 100 ; i++)); do
285 for i in {5..50..5}; do
293 while read -r line; do
310 ### Defining functions
319 # Same as above (alternate syntax)
333 local myresult='some value'
360 | Expression | Description |
361 | ---------- | ---------------------------------------------- |
362 | `$#` | Number of arguments |
363 | `$*` | All positional arguments (as a single word) |
364 | `$@` | All positional arguments (as separate strings) |
365 | `$1` | First argument |
366 | `$_` | Last argument of the previous command |
368 **Note**: `$@` and `$*` must be quoted in order to perform as described.
369 Otherwise, they do exactly the same thing (arguments as separate strings).
371 See [Special parameters](https://web.archive.org/web/20230318164746/https://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
379 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.
381 | Condition | Description |
382 | ------------------------ | --------------------- |
383 | `[[ -z STRING ]]` | Empty string |
384 | `[[ -n STRING ]]` | Not empty string |
385 | `[[ STRING == STRING ]]` | Equal |
386 | `[[ STRING != STRING ]]` | Not Equal |
388 | `[[ NUM -eq NUM ]]` | Equal |
389 | `[[ NUM -ne NUM ]]` | Not equal |
390 | `[[ NUM -lt NUM ]]` | Less than |
391 | `[[ NUM -le NUM ]]` | Less than or equal |
392 | `[[ NUM -gt NUM ]]` | Greater than |
393 | `[[ NUM -ge NUM ]]` | Greater than or equal |
395 | `[[ STRING =~ STRING ]]` | Regexp |
397 | `(( NUM < NUM ))` | Numeric conditions |
401 | Condition | Description |
402 | -------------------- | ------------------------ |
403 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
405 | `[[ ! EXPR ]]` | Not |
406 | `[[ X && Y ]]` | And |
407 | `[[ X || Y ]]` | Or |
411 | Condition | Description |
412 | ----------------------- | ----------------------- |
413 | `[[ -e FILE ]]` | Exists |
414 | `[[ -r FILE ]]` | Readable |
415 | `[[ -h FILE ]]` | Symlink |
416 | `[[ -d FILE ]]` | Directory |
417 | `[[ -w FILE ]]` | Writable |
418 | `[[ -s FILE ]]` | Size is > 0 bytes |
419 | `[[ -f FILE ]]` | File |
420 | `[[ -x FILE ]]` | Executable |
422 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
423 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
424 | `[[ FILE1 -ef FILE2 ]]` | Same files |
430 if [[ -z "$string" ]]; then
431 echo "String is empty"
432 elif [[ -n "$string" ]]; then
433 echo "String is not empty"
435 echo "This never happens"
441 if [[ X && Y ]]; then
448 if [[ "$A" == "$B" ]]
457 if (( $a < $b )); then
458 echo "$a is smaller than $b"
463 if [[ -e "file.txt" ]]; then
473 Fruits=('Apple' 'Banana' 'Orange')
482 ### Working with arrays
485 echo "${Fruits[0]}" # Element #0
486 echo "${Fruits[-1]}" # Last element
487 echo "${Fruits[@]}" # All elements, space-separated
488 echo "${#Fruits[@]}" # Number of elements
489 echo "${#Fruits}" # String length of the 1st element
490 echo "${#Fruits[3]}" # String length of the Nth element
491 echo "${Fruits[@]:3:2}" # Range (from position 3, length 2)
492 echo "${!Fruits[@]}" # Keys of all elements, space-separated
498 Fruits=("${Fruits[@]}" "Watermelon") # Push
499 Fruits+=('Watermelon') # Also Push
500 Fruits=( "${Fruits[@]/Ap*/}" ) # Remove by regex match
501 unset Fruits[2] # Remove one item
502 Fruits=("${Fruits[@]}") # Duplicate
503 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
504 lines=(`cat "logfile"`) # Read from file
510 for i in "${arrayName[@]}"; do
532 Declares `sound` as a Dictionary object (aka associative array).
534 ### Working with dictionaries
537 echo "${sounds[dog]}" # Dog's sound
538 echo "${sounds[@]}" # All values
539 echo "${!sounds[@]}" # All keys
540 echo "${#sounds[@]}" # Number of elements
541 unset sounds[dog] # Delete dog
546 #### Iterate over values
549 for val in "${sounds[@]}"; do
554 #### Iterate over keys
557 for key in "${!sounds[@]}"; do
567 set -o noclobber # Avoid overlay files (echo "hi" > foo)
568 set -o errexit # Used to exit upon error, avoiding cascading errors
569 set -o pipefail # Unveils hidden failures
570 set -o nounset # Exposes unset variables
576 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
577 shopt -s failglob # Non-matching globs throw errors
578 shopt -s nocaseglob # Case insensitive globs
579 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
580 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
583 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
590 | Command | Description |
591 | --------------------- | ----------------------------------------- |
592 | `history` | Show history |
593 | `shopt -s histverify` | Don't execute expanded result immediately |
597 | Expression | Description |
598 | ------------ | ---------------------------------------------------- |
599 | `!$` | Expand last parameter of most recent command |
600 | `!*` | Expand all parameters of most recent command |
601 | `!-n` | Expand `n`th most recent command |
602 | `!n` | Expand `n`th command in history |
603 | `!<command>` | Expand most recent invocation of command `<command>` |
607 | Code | Description |
608 | -------------------- | --------------------------------------------------------------------- |
609 | `!!` | Execute last command again |
610 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
611 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
612 | `!$:t` | Expand only basename from last parameter of most recent command |
613 | `!$:h` | Expand only directory from last parameter of most recent command |
615 `!!` and `!$` can be replaced with any valid expansion.
619 | Code | Description |
620 | -------- | ---------------------------------------------------------------------------------------- |
621 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
622 | `!^` | Expand first argument from most recent command |
623 | `!$` | Expand last token from most recent command |
624 | `!!:n-m` | Expand range of tokens from most recent command |
625 | `!!:n-$` | Expand `n`th token to last from most recent command |
627 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
631 ### Numeric calculations
634 $((a + 200)) # Add 200 to $a
638 $(($RANDOM%200)) # Random number 0..199
642 declare -i count # Declare as type integer
649 (cd somedir; echo "I'm now in $PWD")
650 pwd # still in first directory
656 python hello.py > output.txt # stdout to (file)
657 python hello.py >> output.txt # stdout to (file), append
658 python hello.py 2> error.log # stderr to (file)
659 python hello.py 2>&1 # stderr to stdout
660 python hello.py 2>/dev/null # stderr to (null)
661 python hello.py >output.txt 2>&1 # stdout and stderr to (file), equivalent to &>
662 python hello.py &>/dev/null # stdout and stderr to (null)
663 echo "$0: warning: too many users" >&2 # print diagnostic message to stderr
667 python hello.py < foo.txt # feed foo.txt to stdin for python
668 diff <(ls -r) <(ls) # Compare two stdout without files
671 ### Inspecting commands
675 #=> "cd is a function/alias/whatever"
681 trap 'echo Error at about $LINENO' ERR
688 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
704 echo "Usage: $0 {start|stop|ssh}"
712 source "${0%/*}/../share/foo.sh"
718 printf "Hello %s, I'm %s" Sven Olga
719 #=> "Hello Sven, I'm Olga
721 printf "1 + 1 = %d" 2
724 printf "This is how you print a float: %f" 2
725 #=> "This is how you print a float: 2.000000"
727 printf '%s\n' '#!/bin/bash' 'echo hello' >file
728 # format string is applied to each group of arguments
729 printf '%i+%i=%i\n' 1 2 3 4 5 9
732 ### Transform strings
734 | Command option | Description |
735 | -------------- | --------------------------------------------------- |
736 | `-c` | Operations apply to characters not in the given set |
737 | `-d` | Delete characters |
738 | `-s` | Replaces repeated characters with single occurrence |
740 | `[:upper:]` | All upper case letters |
741 | `[:lower:]` | All lower case letters |
742 | `[:digit:]` | All digits |
743 | `[:space:]` | All whitespace |
744 | `[:alpha:]` | All letters |
745 | `[:alnum:]` | All letters and digits |
750 echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]'
754 ### Directory of script
763 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
775 if [[ "$1" == '--' ]]; then shift; fi
789 echo -n "Proceed? [y/n]: "
794 The `-r` option disables a peculiar legacy behavior with backslashes.
797 read -n 1 ans # Just one character
800 ### Special variables
802 | Expression | Description |
803 | ------------------ | -------------------------------------- |
804 | `$?` | Exit status of last task |
805 | `$!` | PID of last background task |
806 | `$$` | PID of shell |
807 | `$0` | Filename of the shell script |
808 | `$_` | Last argument of the previous command |
809 | `${PIPESTATUS[n]}` | return value of piped commands (array) |
811 See [Special parameters](https://web.archive.org/web/20230318164746/https://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
813 ### Go to previous directory
818 pwd # /home/user/foo/bar
823 ### Check for command's result
826 if ping -c 1 google.com; then
827 echo "It appears you have a working internet connection"
834 if grep -q 'foo' ~/.bash_history; then
835 echo "You appear to have typed 'foo' in the past"
843 - [Bash-hackers wiki](https://web.archive.org/web/20230406205817/https://wiki.bash-hackers.org/) _(bash-hackers.org)_
844 - [Shell vars](https://web.archive.org/web/20230318164746/https://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)_