meta data for this page
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| linux:bash [2016/11/30 08:51] – niziak | linux:bash [2023/11/23 06:57] (current) – niziak | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| ====== Bash ====== | ====== Bash ====== | ||
| + | |||
| + | ===== re-run as other user ===== | ||
| + | |||
| + | <code bash> | ||
| + | if [ $UID == 0 ]; then | ||
| + |     exec su -c " | ||
| + | fi | ||
| + | </ | ||
| + | |||
| + | ===== Check if command is installed ===== | ||
| + | |||
| + | <code bash> | ||
| + | if ! command -v " | ||
| + | echo " Command ${TOOL} not found. Please install it" | ||
| + | exit 1 | ||
| + | fi | ||
| + | </ | ||
| + | |||
| + | and use it inside loop: | ||
| + | <code bash> | ||
| + | for tool in awk bc sed; do | ||
| + | .... | ||
| + | done | ||
| + | </ | ||
| + | |||
| + | ===== Output ===== | ||
| + | |||
| + | <code bash> | ||
| + | DEBUG() { | ||
| + | if [ $DEBUG_ENABLE -eq 1 ]; then | ||
| + | >&2 echo "DBG: $@" | ||
| + | fi | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | ===== Variables with space ===== | ||
| + | |||
| + | <code bash> | ||
| + | # Treat arguments as parts of one argument | ||
| + | declare DST=$* | ||
| + | |||
| + | # Use double colons to pass argument with spaces | ||
| + | nice ionice -c idle btrfs filesystem defragment -v -r -czlib " | ||
| + | </ | ||
| + | |||
| + | Quote problematic characters to use in shell invocation: | ||
| + | <code bash> | ||
| + |   QUOTED_VAR=" | ||
| + | </ | ||
| + | |||
| ===== Default values ===== | ===== Default values ===== | ||
| Line 21: | Line 71: | ||
| done < <(ls -1 /tmp/) | done < <(ls -1 /tmp/) | ||
| </ | </ | ||
| + | |||
| + | ==== ' | ||
| + | In loop where stdin is redirected the easiest way to use read is: | ||
| + | <code bash> | ||
| + | TTY=`tty` | ||
| + | while read ... | ||
| + | do | ||
| + | read CTRLC < ${TTY} | ||
| + | done < somedata | ||
| + | </ | ||
| + | |||
| ===== concatenate output (subshell) ===== | ===== concatenate output (subshell) ===== | ||
| Line 65: | Line 126: | ||
| <code bash> | <code bash> | ||
| - | DIR=" | + | # Works correctly if script is sourced from another one | 
| + | DIR=" | ||
| </ | </ | ||
| <code bash> | <code bash> | ||
| cur_file=" | cur_file=" | ||
| - | cur_dir=" | + | cur_dir=" | 
| </ | </ | ||