blog.mkiesel

about

posts

other

29. Feb 2024

POSIX & Bash Scripting

Prerequisites Check #

tools="tr sed awk sort curl jq"
for tool in $tools; do
    if [ -z "$(which "$tool")" ]; then
        echo "$tool is not installed or in \$PATH"
        exit
    fi
done

Conditions #

If string is empty #

string="notempty"
if [ -z "$string" ]; then
    echo "is empty"
fi

If string is not empty #

string="notempty"
if [ -n "$string" ]; then
    echo "is not empty"
fi

If substring in string #

# https://stackoverflow.com/a/15506990
if echo "$1" | grep -q "$2" > /dev/null; then
    echo "$2 is in $1"
else 
    echo "$2 is not in $1"
fi

If file exists #

if [ -f $FILE ]; then
    echo "$FILE exists"
fi

Loops #

While #

i=0
while [ $i -lt 100 ]; do
    echo "$i"
    i=$(( $i + 1 ))
done

For file in folder #

FILES=$(find PATH -type f)
for FILE in $FILES; do
    echo $FILE
done

Text Manipulation #

Spaces to newlines #

| tr " " "\n" |

Remove newlines #

tr -d '\n'

Remove first line #

| sed 1d

Remove last line #

| tail -n +2 |

To lowercase #

| tr '[:upper:]' '[:lower:]'

To hex #

# src: unknown
echo -n "YourString" | od -A n -t x1 | awk '{for(i=1;i<=NF;i++) printf $i; } END {print ""}'

Switch case #

case $stringtotest in
    *string1*) echo "string 1";;
    *string2*) echo "string 2";;
    *) echo "default";;
esac

Get Data #

Basename #

# will return "file"
basename /path/to/file

File Extension #

file="doc.pdf"
EXT=${FILE##*.}

Specific line #

echo "$text" | awk "NR==42" 
# or
awk "NR==42" file.txt

Random Number #

# src: unknown
awk -v min=1 -v max=10 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')

Grep Regex #

# src: unknown
# matches between {}
| grep -oP '(?<=\{).*(?=\})'

Uniq without sorting #

# https://stackoverflow.com/a/20639730/20963639
cat -n FILE | sort -uk2 | sort -n | cut -f2-
Table of Contents