John Siu Blog

Tech - Business Tool, Personal Toys

Shell - Bash

☰ Table of Content

Bash cheat sheet.

Current directory

1
echo ${PWD##*/}

String Comparison

1
if [ "$str" = "string" ]; then ...

bash/zsh Numeric Comparison

1
if [[ ${A} = 3 ]]; then echo yes; fi

Echo Multiple Lines

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
STR="Line 1
Line2"

# This will output all in one line
echo $STR
Line 1 Line 2

# Use ""
echo "$STR"
Line 1
Line 2

Cut Prefix

Cut shortest match:

1
2
3
$ a=b/c/d/e
$ echo ${a#*/}
c/d/e

Cut longest match:

1
2
3
$ a=b/c/d/e
$ echo ${a##*/}
e

Cut Suffix

Cut shortest match:

1
2
3
$ a=b/c/d/e
$ echo ${a%/*}
b/c/d

Cut longest match:

1
2
3
$ a=b/c/d/e
$ echo ${a%%/*}
b

Search/Replace

${string/<search>/<replace with>}

1
2
3
4
5
6
a="This is a test."
b=" is a "
c=" is not a "
d=${a/$b/$c}
echo ${d}
This is not a test.

Substring

${string:<position>:<length>}. If no :<length>, default till end of string.

1
2
3
4
   0123
a="This"
echo ${a:2}
is

Calculation

1
2
3
4
a=1
((a=a+1))
echo $a
2

Read Line By Line

File

1
2
3
4
file=test.txt
while IFS= read -r line; do
...
done <${file}
  • IFS= change delimiter to new line (\n).
  • IFS default: $' \t\n'

Variable

1
2
3
4
5
6
7
VAR="line 1
line 2
line 3"

while IFS= read -r LINE; do
	echo ${LINE}
done <<<"${VAR}"

John Siu

Update: 2020-08-12
comments powered by Disqus