Search code examples
bashflags

how to pass defaults to flags


I need to pass defaults to the -c -t -u flags. in the -c i need that to be infinite in the -t i need that to be 1 sec and in the -u the defauls is ANY user

#!/bin/bash

set -u

print_usage(){
echo "usage: script[-c] [-t] [-u] exe-name"
}
if [[ $# -eq 0 ]]; then
print_usage
exit 1
fi

while getopts :c:t:u: flag; do
case $flag in
c) counts=$OPTARG;;
t) timeout=$OPTARG;;
u) user_name=$OPTARG;;
esac
done

if [ $counts==true ]
    then
top -n ${counts}
    fi
if [ $timeout==true ]
    then
top -d ${timeout}
    fi
if [ $user_name==true ]
    then
top -u ${user_name}
    fi

I tried to put something like that in the biginning but it doesn't work:

counts=
timeout=1
user_name=.

Solution

  • Assign default values to the variables before the while loop.

    Use arrays for variables that can hold multiple arguments. See Setting an argument with bash for the reasons.

    You can then execute a single top command that has all the arguments combined.

    #!/bin/bash
    
    set -u
    
    print_usage(){
        echo "usage: script [-c repetitions] [-t timeout] [-u username] exe-name"
    }
    if [[ $# -eq 0 ]]; then
        print_usage
        exit 1
    fi
    
    counts=()
    timeout=(-d 1)
    user_name=()
    
    while getopts :c:t:u: flag; do
        case $flag in
            c) counts=(-n "$OPTARG");;
            t) timeout=(-d "$OPTARG");;
            u) user_name=(-u "$OPTARG");;
        esac
    done
    
    top "${counts[@]}" "${timeout[@]}" "${user_name[@]}"