bash.md: update with best practices (#1897)

This commit is contained in:
tripleee 2022-10-30 13:55:55 +02:00 committed by GitHub
parent 6999e947cb
commit 271e0b7c5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 106 additions and 91 deletions

183
bash.md
View File

@ -32,32 +32,39 @@ This is a quick reference to getting started with Bash scripting.
```bash ```bash
#!/usr/bin/env bash #!/usr/bin/env bash
NAME="John" name="John"
echo "Hello $NAME!" echo "Hello $name!"
``` ```
### Variables ### Variables
```bash ```bash
NAME="John" name="John"
echo $NAME echo $name # see below
echo "$NAME" echo "$name"
echo "${NAME}!" echo "${name}!"
```
Generally quote your variables unless they contain wildcards to expand or command fragments.
```bash
wildcard="*.txt"
option="iv"
cp -$options $wildcard /tmp
``` ```
### String quotes ### String quotes
```bash ```bash
NAME="John" name="John"
echo "Hi $NAME" #=> Hi John echo "Hi $name" #=> Hi John
echo 'Hi $NAME' #=> Hi $NAME echo 'Hi $name' #=> Hi $name
``` ```
### Shell execution ### Shell execution
```bash ```bash
echo "I'm in $(pwd)" echo "I'm in $(pwd)"
echo "I'm in `pwd`" echo "I'm in `pwd`" # obsolescent
# Same # Same
``` ```
@ -128,65 +135,65 @@ Parameter expansions
```bash ```bash
name="John" name="John"
echo ${name} echo "${name}"
echo ${name/J/j} #=> "john" (substitution) echo "${name/J/j}" #=> "john" (substitution)
echo ${name:0:2} #=> "Jo" (slicing) echo "${name:0:2}" #=> "Jo" (slicing)
echo ${name::2} #=> "Jo" (slicing) echo "${name::2}" #=> "Jo" (slicing)
echo ${name::-1} #=> "Joh" (slicing) echo "${name::-1}" #=> "Joh" (slicing)
echo ${name:(-1)} #=> "n" (slicing from right) echo "${name:(-1)}" #=> "n" (slicing from right)
echo ${name:(-2):1} #=> "h" (slicing from right) echo "${name:(-2):1}" #=> "h" (slicing from right)
echo ${food:-Cake} #=> $food or "Cake" echo "${food:-Cake}" #=> $food or "Cake"
``` ```
```bash ```bash
length=2 length=2
echo ${name:0:length} #=> "Jo" echo "${name:0:length}" #=> "Jo"
``` ```
See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe) See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
```bash ```bash
STR="/path/to/foo.cpp" str="/path/to/foo.cpp"
echo ${STR%.cpp} # /path/to/foo echo "${str%.cpp}" # /path/to/foo
echo ${STR%.cpp}.o # /path/to/foo.o echo "${str%.cpp}.o" # /path/to/foo.o
echo ${STR%/*} # /path/to echo "${str%/*}" # /path/to
echo ${STR##*.} # cpp (extension) echo "${str##*.}" # cpp (extension)
echo ${STR##*/} # foo.cpp (basepath) echo "${str##*/}" # foo.cpp (basepath)
echo ${STR#*/} # path/to/foo.cpp echo "${str#*/}" # path/to/foo.cpp
echo ${STR##*/} # foo.cpp echo "${str##*/}" # foo.cpp
echo ${STR/foo/bar} # /path/to/bar.cpp echo "${str/foo/bar}" # /path/to/bar.cpp
``` ```
```bash ```bash
STR="Hello world" str="Hello world"
echo ${STR:6:5} # "world" echo "${str:6:5}" # "world"
echo ${STR: -5:5} # "world" echo "${str: -5:5}" # "world"
``` ```
```bash ```bash
SRC="/path/to/foo.cpp" src="/path/to/foo.cpp"
BASE=${SRC##*/} #=> "foo.cpp" (basepath) base=${src##*/} #=> "foo.cpp" (basepath)
DIR=${SRC%$BASE} #=> "/path/to/" (dirpath) dir=${src%$base} #=> "/path/to/" (dirpath)
``` ```
### Substitution ### Substitution
| Code | Description | | Code | Description |
| ----------------- | ------------------- | | ----------------- | ------------------- |
| `${FOO%suffix}` | Remove suffix | | `${foo%suffix}` | Remove suffix |
| `${FOO#prefix}` | Remove prefix | | `${foo#prefix}` | Remove prefix |
| --- | --- | | --- | --- |
| `${FOO%%suffix}` | Remove long suffix | | `${foo%%suffix}` | Remove long suffix |
| `${FOO##prefix}` | Remove long prefix | | `${foo##prefix}` | Remove long prefix |
| --- | --- | | --- | --- |
| `${FOO/from/to}` | Replace first match | | `${foo/from/to}` | Replace first match |
| `${FOO//from/to}` | Replace all | | `${foo//from/to}` | Replace all |
| --- | --- | | --- | --- |
| `${FOO/%from/to}` | Replace suffix | | `${foo/%from/to}` | Replace suffix |
| `${FOO/#from/to}` | Replace prefix | | `${foo/#from/to}` | Replace prefix |
### Comments ### Comments
@ -206,37 +213,37 @@ comment
| Expression | Description | | Expression | Description |
| --------------- | ------------------------------ | | --------------- | ------------------------------ |
| `${FOO:0:3}` | Substring _(position, length)_ | | `${foo:0:3}` | Substring _(position, length)_ |
| `${FOO:(-3):3}` | Substring from the right | | `${foo:(-3):3}` | Substring from the right |
### Length ### Length
| Expression | Description | | Expression | Description |
| ---------- | ---------------- | | ---------- | ---------------- |
| `${#FOO}` | Length of `$FOO` | | `${#foo}` | Length of `$foo` |
### Manipulation ### Manipulation
```bash ```bash
STR="HELLO WORLD!" str="HELLO WORLD!"
echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter) echo "${str,}" #=> "hELLO WORLD!" (lowercase 1st letter)
echo ${STR,,} #=> "hello world!" (all lowercase) echo "${str,,}" #=> "hello world!" (all lowercase)
STR="hello world!" str="hello world!"
echo ${STR^} #=> "Hello world!" (uppercase 1st letter) echo "${str^}" #=> "Hello world!" (uppercase 1st letter)
echo ${STR^^} #=> "HELLO WORLD!" (all uppercase) echo "${str^^}" #=> "HELLO WORLD!" (all uppercase)
``` ```
### Default values ### Default values
| Expression | Description | | Expression | Description |
| ----------------- | -------------------------------------------------------- | | ----------------- | -------------------------------------------------------- |
| `${FOO:-val}` | `$FOO`, or `val` if unset (or null) | | `${foo:-val}` | `$foo`, or `val` if unset (or null) |
| `${FOO:=val}` | Set `$FOO` to `val` if unset (or null) | | `${foo:=val}` | Set `$foo` to `val` if unset (or null) |
| `${FOO:+val}` | `val` if `$FOO` is set (and not null) | | `${foo:+val}` | `val` if `$foo` is set (and not null) |
| `${FOO:?message}` | Show error message and exit if `$FOO` is unset (or null) | | `${foo:?message}` | Show error message and exit if `$foo` is unset (or null) |
Omitting the `:` removes the (non)nullity checks, e.g. `${FOO-val}` expands to `val` if unset otherwise `$FOO`. Omitting the `:` removes the (non)nullity checks, e.g. `${foo-val}` expands to `val` if unset otherwise `$foo`.
Loops Loops
----- -----
@ -246,7 +253,7 @@ Loops
```bash ```bash
for i in /etc/rc.*; do for i in /etc/rc.*; do
echo $i echo "$i"
done done
``` ```
@ -254,7 +261,7 @@ done
```bash ```bash
for ((i = 0 ; i < 100 ; i++)); do for ((i = 0 ; i < 100 ; i++)); do
echo $i echo "$i"
done done
``` ```
@ -277,9 +284,9 @@ done
### Reading lines ### Reading lines
```bash ```bash
cat file.txt | while read line; do while read -r line; do
echo $line echo "$line"
done done <file.txt
``` ```
### Forever ### Forever
@ -318,12 +325,12 @@ myfunc "John"
```bash ```bash
myfunc() { myfunc() {
local myresult='some value' local myresult='some value'
echo $myresult echo "$myresult"
} }
``` ```
```bash ```bash
result="$(myfunc)" result=$(myfunc)
``` ```
### Raising errors ### Raising errors
@ -470,14 +477,14 @@ Fruits[2]="Orange"
### Working with arrays ### Working with arrays
```bash ```bash
echo ${Fruits[0]} # Element #0 echo "${Fruits[0]}" # Element #0
echo ${Fruits[-1]} # Last element echo "${Fruits[-1]}" # Last element
echo ${Fruits[@]} # All elements, space-separated echo "${Fruits[@]}" # All elements, space-separated
echo ${#Fruits[@]} # Number of elements echo "${#Fruits[@]}" # Number of elements
echo ${#Fruits} # String length of the 1st element echo "${#Fruits}" # String length of the 1st element
echo ${#Fruits[3]} # String length of the Nth element echo "${#Fruits[3]}" # String length of the Nth element
echo ${Fruits[@]:3:2} # Range (from position 3, length 2) echo "${Fruits[@]:3:2}" # Range (from position 3, length 2)
echo ${!Fruits[@]} # Keys of all elements, space-separated echo "${!Fruits[@]}" # Keys of all elements, space-separated
``` ```
### Operations ### Operations
@ -485,7 +492,7 @@ echo ${!Fruits[@]} # Keys of all elements, space-separated
```bash ```bash
Fruits=("${Fruits[@]}" "Watermelon") # Push Fruits=("${Fruits[@]}" "Watermelon") # Push
Fruits+=('Watermelon') # Also Push Fruits+=('Watermelon') # Also Push
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match Fruits=( "${Fruits[@]/Ap*/}" ) # Remove by regex match
unset Fruits[2] # Remove one item unset Fruits[2] # Remove one item
Fruits=("${Fruits[@]}") # Duplicate Fruits=("${Fruits[@]}") # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
@ -496,7 +503,7 @@ lines=(`cat "logfile"`) # Read from file
```bash ```bash
for i in "${arrayName[@]}"; do for i in "${arrayName[@]}"; do
echo $i echo "$i"
done done
``` ```
@ -522,10 +529,10 @@ Declares `sound` as a Dictionary object (aka associative array).
### Working with dictionaries ### Working with dictionaries
```bash ```bash
echo ${sounds[dog]} # Dog's sound echo "${sounds[dog]}" # Dog's sound
echo ${sounds[@]} # All values echo "${sounds[@]}" # All values
echo ${!sounds[@]} # All keys echo "${!sounds[@]}" # All keys
echo ${#sounds[@]} # Number of elements echo "${#sounds[@]}" # Number of elements
unset sounds[dog] # Delete dog unset sounds[dog] # Delete dog
``` ```
@ -535,7 +542,7 @@ unset sounds[dog] # Delete dog
```bash ```bash
for val in "${sounds[@]}"; do for val in "${sounds[@]}"; do
echo $val echo "$val"
done done
``` ```
@ -543,7 +550,7 @@ done
```bash ```bash
for key in "${!sounds[@]}"; do for key in "${!sounds[@]}"; do
echo $key echo "$key"
done done
``` ```
@ -645,7 +652,9 @@ python hello.py >> output.txt # stdout to (file), append
python hello.py 2> error.log # stderr to (file) python hello.py 2> error.log # stderr to (file)
python hello.py 2>&1 # stderr to stdout python hello.py 2>&1 # stderr to stdout
python hello.py 2>/dev/null # stderr to (null) python hello.py 2>/dev/null # stderr to (null)
python hello.py >output.txt 2>&1 # stdout and stderr to (file), equivalent to &>
python hello.py &>/dev/null # stdout and stderr to (null) python hello.py &>/dev/null # stdout and stderr to (null)
echo "$0: warning: too many users" >&2 # print diagnostic message to stderr
``` ```
```bash ```bash
@ -708,6 +717,10 @@ printf "1 + 1 = %d" 2
printf "This is how you print a float: %f" 2 printf "This is how you print a float: %f" 2
#=> "This is how you print a float: 2.000000" #=> "This is how you print a float: 2.000000"
printf '%s\n' '#!/bin/bash' 'echo hello' >file
# format string is applied to each group of arguments
printf '%i+%i=%i\n' 1 2 3 4 5 9
``` ```
### Transform strings ### Transform strings
@ -728,14 +741,14 @@ printf "This is how you print a float: %f" 2
#### Example #### Example
```bash ```bash
echo "Welcome To Devhints" | tr [:lower:] [:upper:] echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]'
WELCOME TO DEVHINTS WELCOME TO DEVHINTS
``` ```
### Directory of script ### Directory of script
```bash ```bash
DIR="${0%/*}" dir=${0%/*}
``` ```
### Getting options ### Getting options
@ -743,7 +756,7 @@ DIR="${0%/*}"
```bash ```bash
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-V | --version ) -V | --version )
echo $version echo "$version"
exit exit
;; ;;
-s | --string ) -s | --string )
@ -768,10 +781,12 @@ END
```bash ```bash
echo -n "Proceed? [y/n]: " echo -n "Proceed? [y/n]: "
read ans read -r ans
echo $ans echo "$ans"
``` ```
The `-r` option disables a peculiar legacy behavior with backslashes.
```bash ```bash
read -n 1 ans # Just one character read -n 1 ans # Just one character
``` ```