71 lines
1.0 KiB
Markdown
71 lines
1.0 KiB
Markdown
# Bash Tips
|
|
|
|
## prevent last false
|
|
|
|
function body should not end up with a ternary statement
|
|
|
|
### wrong last
|
|
|
|
Compound of 2 'false' statement returns false.
|
|
|
|
```bash
|
|
[[ : ]] && [[ : ]]
|
|
```
|
|
|
|
### right last
|
|
|
|
```bash
|
|
[[ : ]] && [[ : ]] || true
|
|
```
|
|
|
|
## arithmetic issue
|
|
|
|
last (++) statement does not complete successfully!
|
|
|
|
### wrong ++
|
|
|
|
```bash
|
|
count=0
|
|
(( ++count )) # ok
|
|
(( ++count )) # last statement in function returns false
|
|
```
|
|
|
|
### right ++
|
|
|
|
```bash
|
|
count=0
|
|
count=$((count+1))
|
|
```
|
|
|
|
## properly grab $?
|
|
|
|
> prefer plain `command` rather than `! command`
|
|
> otherwise you will miss out the exit code
|
|
|
|
### wrong if
|
|
|
|
```bash
|
|
if ! command; then
|
|
local code=$?
|
|
>&2 echo $code # => 0
|
|
fi
|
|
```
|
|
|
|
### right if
|
|
|
|
```bash
|
|
if command; then
|
|
: # useful for preserving $?
|
|
else
|
|
local code=$?
|
|
>&2 echo $code
|
|
fi
|
|
```
|
|
|
|
## sudo -E or better source if already root
|
|
|
|
From within a miaou-bash script and in case sudo is required
|
|
|
|
1. prefer using source if already root
|
|
2. or force preserving the MIAOU_BASH_DIR environment variable with `sudo -E
|