The ugliest language in the world.

Parse Command Line Arguments

Often we want to parse command line arguments when executing a bash script, to make the script usable on different things.

It’s a typical use case for a command line tool.

Say you want to do something like:

sh ./something.txt

The variable ./something.txt will be available in $1 inside of your bash script.

Similarly, if you run:

sh ./something.txt ./things/something2.txt

There will be two variables available, $1 and $2.

Parse NAMED Command Line Arguments

Like the above, except when we need to name them…

# sh ./ -t dog -a bruh -f 123
while getopts t:a:f: flag
    case "${flag}" in
        t) tag=${OPTARG};;
        a) noop=${OPTARG};;
        f) noop2=${OPTARG};;

Get the current directory

Like node’s __dirname, bash you do this:

dirname $0

Here, $0 refers to the bash script itself.

Set a variable and concatenate it

e.g., if we’re counting dogs…

NOW=$(date +"%T")
echo "$NOW:$DOG_NUM" >> dog-log.txt

Capture the output of a command into a variable

Using these things: $()

echo "$ME"

Interpolating a Variable in a JSON String

See this stackoverflow answer.

Godsend for portable scripting when debugging.

DATA='{"email":"john4'$(date +"%s")'","password":"123456"}'
curl --request POST \
--url \
--header 'Content-Type: application/json' \
--data "$DATA"
Last modified: January 12, 2022
© 2024