Bash Basic

Bash Basic

Donny Donny
November 27, 2018
June 27, 2022
730
-

Tags in blue are handcrafted tags; Tags in green are generated using AutoTag.

Substitution, dirname, basename and suffix

Substitution can be used to get path and short filename.

filename=a/b/c/name.file
echo ${filename#*/}     # b/c/name.file
echo ${filename##*/}    # name.file
echo ${filename%/*}     # a/b/c
echo ${filename%%/*}    # a

But in fact, there is better way:

filename=a/b/c/name.file
echo $(dirname $filename)
echo $(basename $filename)

Still, substitution is useful for getting filename without suffix or getting suffix.

filename=file.name.type
echo ${filename%.*}     # file.name
echo ${filename##*.}    # type

Parameter Expansion

String selection:

string=1234567890abcdefg
echo ${string: 10}      # abcdefg
echo ${string: 10:5}    # abcde
echo ${string: 7:-4}    # 890abc

Array selection:

arr=(0 1 2)
arr=(${arr[@]} 'a' 'b' 'c')
echo ${arr[@]}         # 0 1 2 a b c
echo ${#arr[@]}        # 6 (the length of the arry)
echo ${arr[@]: 3:2}    # a b
echo ${arr[3]}         # a

For more, refer to Bash Reference Manual: Shell Parameter Expansion

Expression

Condition expression:

if [[ 1 == 0 ]]; then
    echo "Improssible."        # Won't execute
elif [[ 1 == $(( 0 + 1 )) ]]; then
    echo "Arithmetic work."    # Will exectute
fi

if [[ ! -f "/etc/environment" ]]; then
    echo "What? Environment file missing?!"    # test if the file does not exist
fi

if [[ -d "/boot" ]]; then
    echo "You can boot."    # test if the directory exists
fi

if [[ -z "" ]]; then
    echo "Empty string!"    # test if the string is empty
fi

Loop expression:

for file in *.mp4; do
    if [[ -f $file ]]; then
        ffmpeg -i $file -codec:a copy ${file%.*}
    fi
done

Dead loop:

while [[ 1 ]]; do [[ 1 ]]; done

Arithmetic

Simple calculation:

a=$(( (2+6)*8/4 ))
echo $a    # 16

Float calculation:

b=$(bc -l <<< "10/6")
echo $b    # 1.66666666666666666666

b=$(bc -l <<< "scale=2; 10/6")
echo $b    # 1.66

b=$(printf "%0.2f" $(bc -l <<< "10/6"))
echo $b    # 1.67

Convert Lines to Array

Convert a multi-lines string to an array. Each line will be an item in the array.

IFS=$'\n' read -d '' -r -a arr <<< "$lines"

# lines:
#   a b.txt
#   a.txt

# arr:
#   0: a b.txt
#   1: a.txt

Coloring

Shell Coloring

ターミナルプロンプトの表示・色の変更

sed, awk and grep

sed, awk, grepの使い分け

Acknowledgement

The poster comes from Free Software Foundation.