Greg
Greg

Reputation: 737

bash getopts multiple arguments or default value

So I have a question about get opts in bash. I want to get the value of the arguments if they are present but if they are not present to use a default value. So the script should take a directory and an integer but if they aren't specified then $PWD and 3 should be default values. Here is what

while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        \? ) usage
        exit 1;;
    esac

Upvotes: 15

Views: 24625

Answers (2)

Puffy
Puffy

Reputation: 49

After your getopts, try this

if [ -z "$directory" ]; then directory="directory"; fi

-z means if the variable $directory is null or empty. Then if user doesnt enter an argument for -d, then the script will default to directory="/whatever/files/"

At least if I understand your question correctly, this should give you a default value for -d if a value is not entered.

Upvotes: 2

anubhava
anubhava

Reputation: 784958

You can just provide default value before while loop:

directory=mydir
depth=123
while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        *) usage
        exit 1;;
    esac
done
echo "<$directory> <$depth>"

Upvotes: 31

Related Questions