Taking Command Line Arguments in Bash

Pass arguments through to another program

#!/bin/bash
# print_args.sh
echo "You provided the arguments:" "$@"

# You could pass all arguments to another program like this
# myProgram "$@"

Get the number of arguments passed

#!/bin/bash
echo "You provided $# arguments"

Accessing a specific argument by index

#!/bin/bash
echo "Arg 0: $0"
echo "Arg 1: $1"
echo "Arg 2: $2"

Argument 0 is the name of the script being invoked itself.

Iterating through each argument

#!/bin/bash
for arg in "$@"
do
    echo "$arg"
done

Check arguments for specific value

#!/bin/bash
for arg in "$@"
do
    if [ "$arg" == "--help" ] || [ "$arg" == "-h" ]
    then
        echo "Help argument detected."
    fi
done

References
https://www.devdungeon.com/content/taking-command-line-arguments-bash

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.