Defining flag parameters in bash

Michał Turczyn :

I wrote bash script, in which I included some logging, to see what is going on in each step of exectuion.

Now, I can split those logs in debuggin info and user info (that something has completed, etc.). So I'd like to have some flag parameter, like --verbose, which I saw in some other bash functions to enable full logging and usage was like:

some_function --verbose

or

some_function -v

I call it flag parameters and don't know what's the right name, thus I can't find anything useful.

How to define such parameters for bash script?

Ivan :

Case suits better for this

while [[ "$@" ]]; do
    case "$1" in
        -v|--verbose) verbose="true";;
    esac
    shift
done

Same can be done in function, but note that in this case it'll process parameters passed to function some_function -v.

some_function () {
    while [[ "$@" ]]; do
        case "$1" in
            -v|--verbose) verbose="true";;
        esac
        shift
    done
}

Then somewhere in script you can check if verbose is set

[[ "$verbose" ]] && echo "verbose mode" || echo "silent mode"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21808&siteId=1