skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    For now, I used workaround and take it as normal positional parameter (as $n). To be exact, I have list of four parameters, so I collect this flag like this:

    verbose=$4
    if [ ! "$verbose" == "--verbose" ]; then
      verbose=""
    fi
    

    So, if parameter is not matching a flag, then I leave it empty and if I want to use it, I just compare it against empty string.

    There's one big disadvantage for me though: it has to be at 4th position in parameters list.


  2. 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search