💾 Archived View for gemini.susa.net › bash_notes.gmi captured on 2022-07-16 at 13:41:43. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2021-11-30)

➡️ Next capture (2023-01-29)

-=-=-=-=-=-=-

Bash Cheat Sheet of sorts

The following are notes on bash usage that I often need to refer to.

String Operations

length      ${#MYVAR}
substring   ${MYVAR:2}, ${MYVAR, 0, 4} (third parameter is length)
  from end  ${MYVAR:(-4)} (avoid :- interpreted as default)
  with vars ${MYVAR:$START:$LEN}

parameters  ${*:1} or ${@:1} (positional parameter)
  multi     ${*:2:3} three parameters starting from the second
${MYVAR#/home}   delete shortest match from start of string
${MYVAR##/home}  delete longest match from start of string
${MYVAR%.exe}    delete shortest match from end of string
${MYVAR%%.exe}   delete longest match from end of string
${MYVAR%%$SUFF}  can use a variable

${MYVAR##gemini*cgi-bin}  delete longest match with wildcard

Suppose MYVAR='mykey=myvalue', then

  ${MYVAR%%=*}    yields 'mykey' (delete =* from end of string)
  ${MYVAR##*=}    yields 'myvalue' (delete *= from start of string)
substitute      ${MYVAR/old/new}
  all           ${MYVAR//old/new}
  delete        ${MYVAR/old}
  delete all    ${MYVAR//old}
  at start      ${MYVAR/#usr/var}
  at end        ${MYVAR/%.exe/.sh}

Remove whitespace and newlines: ${MYVAR//[ \t\r\n ']}


## Arithmetic Operations

A=$((4 + 7))

B=$((A + 1))

(( C = B * 2 ))

let "D = $C - 5"


'let' expressions are best quoted, since this allows spaces to be used. Note that variable names need not be preceded by $.

'expr' can be used if 'let' is unavailable. It requires each operator and operand to be separated by spaces.

## Command Grouping

{ } - group commands in the current shell

( ) - group commands in a new shell

e.g. { echo "Line 1"; echo "Line 2" } >two_lines.txt

[[ ]] - conditionals using bash built-in evaluation

(( )) - bash arithmetic grouping (( a=5, a=a*a, b=a+a ))


## Regular Expressions

The following example uses a regualar expression to parse out the bits of a gemini URL.

!/bin/bash

URL=${1}

Reads, gemini:// then host up to an optional port & optional path

if [[ "${URL}" =~ (gemini://)([^:/]+):?([0-9]+)?(/.*)? ]]; then

SCHEME=${BASH_REMATCH[1]}

HOST=${BASH_REMATCH[2]}

PORT=${BASH_REMATCH[3]}

URLPATH=${BASH_REMATCH[4]}

echo "Host ${HOST}, port ${PORT:-1965} ${URLPATH}"

fi