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)_
52 echo "Hi $NAME" #=> Hi John
53 echo 'Hi $NAME' #=> Hi $NAME
64 See [Command substitution](http://wiki.bash-hackers.org/syntax/expansion/cmdsubst)
66 ### Conditional execution
69 git commit && git push
70 git commit || echo "Commit failed"
74 {: id='functions-example'}
81 echo "You are $(get_name)"
84 See: [Functions](#functions)
87 {: id='conditionals-example'}
90 if [[ -z "$string" ]]; then
91 echo "String is empty"
92 elif [[ -n "$string" ]]; then
93 echo "String is not empty"
97 See: [Conditionals](#conditionals)
106 See: [Unofficial bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
114 | Expression | Description |
115 | ---------- | ------------------- |
116 | `{A,B}` | Same as `A B` |
117 | `{A,B}.js` | Same as `A.js B.js` |
118 | `{1..5}` | Same as `1 2 3 4 5` |
120 See: [Brace expansion](http://wiki.bash-hackers.org/syntax/expansion/brace)
132 echo ${name/J/j} #=> "john" (substitution)
133 echo ${name:0:2} #=> "Jo" (slicing)
134 echo ${name::2} #=> "Jo" (slicing)
135 echo ${name::-1} #=> "Joh" (slicing)
136 echo ${name:(-1)} #=> "n" (slicing from right)
137 echo ${name:(-2):1} #=> "h" (slicing from right)
138 echo ${food:-Cake} #=> $food or "Cake"
143 echo ${name:0:length} #=> "Jo"
146 See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
149 STR="/path/to/foo.cpp"
150 echo ${STR%.cpp} # /path/to/foo
151 echo ${STR%.cpp}.o # /path/to/foo.o
152 echo ${STR%/*} # /path/to
154 echo ${STR##*.} # cpp (extension)
155 echo ${STR##*/} # foo.cpp (basepath)
157 echo ${STR#*/} # path/to/foo.cpp
158 echo ${STR##*/} # foo.cpp
160 echo ${STR/foo/bar} # /path/to/bar.cpp
165 echo ${STR:6:5} # "world"
166 echo ${STR: -5:5} # "world"
170 SRC="/path/to/foo.cpp"
171 BASE=${SRC##*/} #=> "foo.cpp" (basepath)
172 DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
177 | Code | Description |
178 | ----------------- | ------------------- |
179 | `${FOO%suffix}` | Remove suffix |
180 | `${FOO#prefix}` | Remove prefix |
182 | `${FOO%%suffix}` | Remove long suffix |
183 | `${FOO##prefix}` | Remove long prefix |
185 | `${FOO/from/to}` | Replace first match |
186 | `${FOO//from/to}` | Replace all |
188 | `${FOO/%from/to}` | Replace suffix |
189 | `${FOO/#from/to}` | Replace prefix |
194 # Single line comment
207 | Expression | Description |
208 | --------------- | ------------------------------ |
209 | `${FOO:0:3}` | Substring _(position, length)_ |
210 | `${FOO:(-3):3}` | Substring from the right |
214 | Expression | Description |
215 | ---------- | ---------------- |
216 | `${#FOO}` | Length of `$FOO` |
222 echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
223 echo ${STR,,} #=> "hello world!" (all lowercase)
226 echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
227 echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
232 | Expression | Description |
233 | ----------------- | -------------------------------------------------------- |
234 | `${FOO:-val}` | `$FOO`, or `val` if unset (or null) |
235 | `${FOO:=val}` | Set `$FOO` to `val` if unset (or null) |
236 | `${FOO:+val}` | `val` if `$FOO` is set (and not null) |
237 | `${FOO:?message}` | Show error message and exit if `$FOO` is unset (or null) |
239 Omitting the `:` removes the (non)nullity checks, e.g. `${FOO-val}` expands to `val` if unset otherwise `$FOO`.
248 for i in /etc/rc.*; do
256 for ((i = 0 ; i < 100 ; i++)); do
272 for i in {5..50..5}; do
280 cat file.txt | while read line; do
297 ### Defining functions
306 # Same as above (alternate syntax)
320 local myresult='some value'
347 | Expression | Description |
349 | `$#` | Number of arguments |
350 | `$*` | All positional arguments (as a single word) |
351 | `$@` | All positional arguments (as separate strings) |
352 | `$1` | First argument |
353 | `$_` | Last argument of the previous command |
355 **Note**: `$@` and `$*` must be quoted in order to perform as described.
356 Otherwise, they do exactly the same thing (arguments as separate strings).
358 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
366 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.
368 | Condition | Description |
370 | `[[ -z STRING ]]` | Empty string |
371 | `[[ -n STRING ]]` | Not empty string |
372 | `[[ STRING == STRING ]]` | Equal |
373 | `[[ STRING != STRING ]]` | Not Equal |
375 | `[[ NUM -eq NUM ]]` | Equal |
376 | `[[ NUM -ne NUM ]]` | Not equal |
377 | `[[ NUM -lt NUM ]]` | Less than |
378 | `[[ NUM -le NUM ]]` | Less than or equal |
379 | `[[ NUM -gt NUM ]]` | Greater than |
380 | `[[ NUM -ge NUM ]]` | Greater than or equal |
382 | `[[ STRING =~ STRING ]]` | Regexp |
384 | `(( NUM < NUM ))` | Numeric conditions |
388 | Condition | Description |
389 | -------------------- | ------------------------ |
390 | `[[ -o noclobber ]]` | If OPTIONNAME is enabled |
392 | `[[ ! EXPR ]]` | Not |
393 | `[[ X && Y ]]` | And |
394 | `[[ X || Y ]]` | Or |
398 | Condition | Description |
400 | `[[ -e FILE ]]` | Exists |
401 | `[[ -r FILE ]]` | Readable |
402 | `[[ -h FILE ]]` | Symlink |
403 | `[[ -d FILE ]]` | Directory |
404 | `[[ -w FILE ]]` | Writable |
405 | `[[ -s FILE ]]` | Size is > 0 bytes |
406 | `[[ -f FILE ]]` | File |
407 | `[[ -x FILE ]]` | Executable |
409 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
410 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
411 | `[[ FILE1 -ef FILE2 ]]` | Same files |
417 if [[ -z "$string" ]]; then
418 echo "String is empty"
419 elif [[ -n "$string" ]]; then
420 echo "String is not empty"
422 echo "This never happens"
428 if [[ X && Y ]]; then
435 if [[ "$A" == "$B" ]]
444 if (( $a < $b )); then
445 echo "$a is smaller than $b"
450 if [[ -e "file.txt" ]]; then
461 Fruits=('Apple' 'Banana' 'Orange')
470 ### Working with arrays
473 echo ${Fruits[0]} # Element #0
474 echo ${Fruits[-1]} # Last element
475 echo ${Fruits[@]} # All elements, space-separated
476 echo ${#Fruits[@]} # Number of elements
477 echo ${#Fruits} # String length of the 1st element
478 echo ${#Fruits[3]} # String length of the Nth element
479 echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
480 echo ${!Fruits[@]} # Keys of all elements, space-separated
486 Fruits=("${Fruits[@]}" "Watermelon") # Push
487 Fruits+=('Watermelon') # Also Push
488 Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
489 unset Fruits[2] # Remove one item
490 Fruits=("${Fruits[@]}") # Duplicate
491 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
492 lines=(`cat "logfile"`) # Read from file
498 for i in "${arrayName[@]}"; do
520 Declares `sound` as a Dictionary object (aka associative array).
522 ### Working with dictionaries
525 echo ${sounds[dog]} # Dog's sound
526 echo ${sounds[@]} # All values
527 echo ${!sounds[@]} # All keys
528 echo ${#sounds[@]} # Number of elements
529 unset sounds[dog] # Delete dog
534 #### Iterate over values
537 for val in "${sounds[@]}"; do
542 #### Iterate over keys
545 for key in "${!sounds[@]}"; do
556 set -o noclobber # Avoid overlay files (echo "hi" > foo)
557 set -o errexit # Used to exit upon error, avoiding cascading errors
558 set -o pipefail # Unveils hidden failures
559 set -o nounset # Exposes unset variables
565 shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
566 shopt -s failglob # Non-matching globs throw errors
567 shopt -s nocaseglob # Case insensitive globs
568 shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
569 shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
572 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
580 | Command | Description |
581 | --------------------- | ----------------------------------------- |
582 | `history` | Show history |
583 | `shopt -s histverify` | Don't execute expanded result immediately |
587 | Expression | Description |
588 | ------------ | ---------------------------------------------------- |
589 | `!$` | Expand last parameter of most recent command |
590 | `!*` | Expand all parameters of most recent command |
591 | `!-n` | Expand `n`th most recent command |
592 | `!n` | Expand `n`th command in history |
593 | `!<command>` | Expand most recent invocation of command `<command>` |
597 | Code | Description |
598 | -------------------- | --------------------------------------------------------------------- |
599 | `!!` | Execute last command again |
600 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
601 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
602 | `!$:t` | Expand only basename from last parameter of most recent command |
603 | `!$:h` | Expand only directory from last parameter of most recent command |
605 `!!` and `!$` can be replaced with any valid expansion.
609 | Code | Description |
610 | -------- | ---------------------------------------------------------------------------------------- |
611 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
612 | `!^` | Expand first argument from most recent command |
613 | `!$` | Expand last token from most recent command |
614 | `!!:n-m` | Expand range of tokens from most recent command |
615 | `!!:n-$` | Expand `n`th token to last from most recent command |
617 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
623 ### Numeric calculations
626 $((a + 200)) # Add 200 to $a
630 $(($RANDOM%200)) # Random number 0..199
636 (cd somedir; echo "I'm now in $PWD")
637 pwd # still in first directory
643 python hello.py > output.txt # stdout to (file)
644 python hello.py >> output.txt # stdout to (file), append
645 python hello.py 2> error.log # stderr to (file)
646 python hello.py 2>&1 # stderr to stdout
647 python hello.py 2>/dev/null # stderr to (null)
648 python hello.py &>/dev/null # stdout and stderr to (null)
652 python hello.py < foo.txt # feed foo.txt to stdin for python
653 diff <(ls -r) <(ls) # Compare two stdout without files
656 ### Inspecting commands
660 #=> "cd is a function/alias/whatever"
666 trap 'echo Error at about $LINENO' ERR
673 echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
689 echo "Usage: $0 {start|stop|ssh}"
697 source "${0%/*}/../share/foo.sh"
703 printf "Hello %s, I'm %s" Sven Olga
704 #=> "Hello Sven, I'm Olga
706 printf "1 + 1 = %d" 2
709 printf "This is how you print a float: %f" 2
710 #=> "This is how you print a float: 2.000000"
713 ### Transform strings
715 | Command option | Description |
716 | ------------------ | --------------------------------------------------- |
717 | `-c` | Operations apply to characters not in the given set |
718 | `-d` | Delete characters |
719 | `-s` | Replaces repeated characters with single occurrence |
721 | `[:upper:]` | All upper case letters |
722 | `[:lower:]` | All lower case letters |
723 | `[:digit:]` | All digits |
724 | `[:space:]` | All whitespace |
725 | `[:alpha:]` | All letters |
726 | `[:alnum:]` | All letters and digits |
731 echo "Welcome To Devhints" | tr [:lower:] [:upper:]
735 ### Directory of script
744 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
756 if [[ "$1" == '--' ]]; then shift; fi
770 echo -n "Proceed? [y/n]: "
776 read -n 1 ans # Just one character
779 ### Special variables
781 | Expression | Description |
782 | ------------------ | -------------------------------------- |
783 | `$?` | Exit status of last task |
784 | `$!` | PID of last background task |
785 | `$$` | PID of shell |
786 | `$0` | Filename of the shell script |
787 | `$_` | Last argument of the previous command |
788 | `${PIPESTATUS[n]}` | return value of piped commands (array) |
790 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
792 ### Go to previous directory
797 pwd # /home/user/foo/bar
802 ### Check for command's result
805 if ping -c 1 google.com; then
806 echo "It appears you have a working internet connection"
813 if grep -q 'foo' ~/.bash_history; then
814 echo "You appear to have typed 'foo' in the past"
821 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
822 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
823 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
824 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
825 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_