How to get arguments with flags in Bash

后端 未结 11 2109
余生分开走
余生分开走 2020-12-22 15:56

I know that I can easily get positioned parameters like this in bash:

$0 or $1

I want to be able to use flag options like this to s

11条回答
  •  萌比男神i
    2020-12-22 16:02

    I like Robert McMahan's answer the best here as it seems the easiest to make into sharable include files for any of your scripts to use. But it seems to have a flaw with the line if [[ -n ${variables[$argument_label]} ]] throwing the message, "variables: bad array subscript". I don't have the rep to comment, and I doubt this is the proper 'fix,' but wrapping that if in if [[ -n $argument_label ]] ; then cleans it up.

    Here's the code I ended up with, if you know a better way please add a comment to Robert's answer.

    Include File "flags-declares.sh"

    # declaring a couple of associative arrays
    declare -A arguments=();
    declare -A variables=();
    
    # declaring an index integer
    declare -i index=1;
    

    Include File "flags-arguments.sh"

    # $@ here represents all arguments passed in
    for i in "$@"
    do
      arguments[$index]=$i;
      prev_index="$(expr $index - 1)";
    
      # this if block does something akin to "where $i contains ="
      # "%=*" here strips out everything from the = to the end of the argument leaving only the label
      if [[ $i == *"="* ]]
        then argument_label=${i%=*}
        else argument_label=${arguments[$prev_index]}
      fi
    
      if [[ -n $argument_label ]] ; then
        # this if block only evaluates to true if the argument label exists in the variables array
        if [[ -n ${variables[$argument_label]} ]] ; then
          # dynamically creating variables names using declare
          # "#$argument_label=" here strips out the label leaving only the value
          if [[ $i == *"="* ]]
            then declare ${variables[$argument_label]}=${i#$argument_label=} 
            else declare ${variables[$argument_label]}=${arguments[$index]}
          fi
        fi
      fi
    
      index=index+1;
    done;
    

    Your "script.sh"

    . bin/includes/flags-declares.sh
    
    # any variables you want to use here
    # on the left left side is argument label or key (entered at the command line along with it's value) 
    # on the right side is the variable name the value of these arguments should be mapped to.
    # (the examples above show how these are being passed into this script)
    variables["-gu"]="git_user";
    variables["--git-user"]="git_user";
    variables["-gb"]="git_branch";
    variables["--git-branch"]="git_branch";
    variables["-dbr"]="db_fqdn";
    variables["--db-redirect"]="db_fqdn";
    variables["-e"]="environment";
    variables["--environment"]="environment";
    
    . bin/includes/flags-arguments.sh
    
    # then you could simply use the variables like so:
    echo "$git_user";
    echo "$git_branch";
    echo "$db_fqdn";
    echo "$environment";
    

提交回复
热议问题