meta data for this page
  •  

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
linux:bash [2016/11/30 08:51] niziaklinux:bash [2022/11/30 10:04] niziak
Line 1: Line 1:
 ====== Bash ====== ====== Bash ======
 +===== rerun as other user =====
 +
 +<code bash>
 +if [ $UID == 0 ]; then
 +    exec su -c "$0" fos4x
 +fi
 +</code>
 +
 +===== Check if command is installed =====
 +
 +<code bash>
 +if ! command -v "${TOOL}" &>/dev/null; then
 +    echo " Command ${TOOL} not found. Please install it"
 +    exit 1
 +fi
 +</code>
 +
 +===== Output =====
 +
 +<code bash>
 +DEBUG() {
 +    if [ $DEBUG_ENABLE -eq 1 ]; then
 +    >&2 echo "DBG: $@"
 +    fi
 +}
 +</code>
 +
 +===== 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 "${DST}"
 +</code>
 +
 +Quote problematic characters to use in shell invocation:
 +<code bash>
 +  QUOTED_VAR="${VAR@Q}"
 +</code>
 +
  
 ===== Default values ===== ===== Default values =====
Line 21: Line 63:
 done < <(ls -1 /tmp/) done < <(ls -1 /tmp/)
 </code> </code>
 +
 +==== 'read' insid loop ====
 +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
 +</code>
 +
  
 ===== concatenate output (subshell) ===== ===== concatenate output (subshell) =====
Line 65: Line 118:
  
 <code bash> <code bash>
-DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd -P "$( dirname "$SOURCE" )" && pwd )"+# Works correctly if script is sourced from another one 
 +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
 </code> </code>
  
 <code bash> <code bash>
 cur_file="${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}" cur_file="${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"
-cur_dir="$(dirname "${cur_file}")+cur_dir="$(dirname "${cur_file}")"
 </code> </code>