Як отримати аргументи зі прапорами у Bash


283

Я знаю, що я можу легко отримати такі позиційні параметри в bash:

$0 або $1

Я хочу мати можливість використовувати такі параметри прапора, щоб вказати, для чого використовується кожен параметр:

mysql -u user -h host

Який найкращий спосіб отримати -u paramзначення та -h paramзначення за прапором, а не за позицією?


2
Можливо, буде гарною ідеєю також запитати / перевірити на unix.stackexchange.com також
MRR0GERS

8
google для "bash getopts" - багато навчальних посібників.
glenn jackman

89
@ glenn-jackman: Напевно я погуглю його зараз, коли знаю ім'я. Справа в Google - щоб задати питання - ви вже повинні знати 50% відповіді.
Стенн

Відповіді:


292

Це ідіома, якою я зазвичай користуюся:

while test $# -gt 0; do
  case "$1" in
    -h|--help)
      echo "$package - attempt to capture frames"
      echo " "
      echo "$package [options] application [arguments]"
      echo " "
      echo "options:"
      echo "-h, --help                show brief help"
      echo "-a, --action=ACTION       specify an action to use"
      echo "-o, --output-dir=DIR      specify a directory to store output in"
      exit 0
      ;;
    -a)
      shift
      if test $# -gt 0; then
        export PROCESS=$1
      else
        echo "no process specified"
        exit 1
      fi
      shift
      ;;
    --action*)
      export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    -o)
      shift
      if test $# -gt 0; then
        export OUTPUT=$1
      else
        echo "no output dir specified"
        exit 1
      fi
      shift
      ;;
    --output-dir*)
      export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    *)
      break
      ;;
  esac
done

Ключові моменти:

  • $# - кількість аргументів
  • в той час як цикл розглядає всі надані аргументи, узгоджуючи їх значення всередині оператора case
  • зміна забирає першу. Ви можете змістити кілька разів всередині оператора, щоб прийняти кілька значень.

3
Що робить --action*і --output-dir*справи?
Лусіо

1
Вони просто зберігають цінності, які вони потрапляють у навколишнє середовище.
Flexo

22
@Lucio Супер старий коментар, але додаючи його у випадку, якщо хто-небудь ще завітає на цю сторінку. * (Підстановка) призначена для випадків, коли хтось набирає --action=[ACTION], а також випадків, коли хтось набирає--action [ACTION]
cooper

2
Чому *)ви зламаєтесь там, не варто виходити чи ігнорувати поганий варіант? Іншими словами частину ніколи не обробляється. -bad -o dir-o dir
newguy

@newguy гарне запитання. Я думаю, я намагався дозволити їм потрапити до чогось іншого
Flexo

427

У цьому прикладі використовується вбудована getoptsкоманда Bash і є з посібника зі стилю Google Shell :

a_flag=''
b_flag=''
files=''
verbose='false'

print_usage() {
  printf "Usage: ..."
}

while getopts 'abf:v' flag; do
  case "${flag}" in
    a) a_flag='true' ;;
    b) b_flag='true' ;;
    f) files="${OPTARG}" ;;
    v) verbose='true' ;;
    *) print_usage
       exit 1 ;;
  esac
done

Примітка: Якщо за символом слідує двокрапка (наприклад f:), очікується, що цей параметр має аргумент.

Приклад використання: ./script -v -a -b -f filename

Використання getopts має ряд переваг перед прийнятою відповіддю:

  • в той час як умова набагато легше читається і показує, які є прийняті варіанти
  • чистіший код; відсутність підрахунку кількості параметрів і зміщення
  • Ви можете приєднатись до параметрів (наприклад, -a -b -c-abc)

Однак великим недоліком є ​​те, що він не підтримує довгі варіанти, а лише односимвольні параметри.


48
Одне цікавить, чому ця відповідь, використовуючи вбудований удар, не є найкращим
Буде Барнвелл

13
Для нащадків: двокрапка після в 'abf: v' позначає, що -f приймає додатковий аргумент (назва файлу в цьому випадку).
zahbaz

1
Мені довелося змінити рядок помилок на це:?) printf '\nUsage: %s: [-a] aflag [-b] bflag\n' $0; exit 2 ;;
Енді

7
Не могли б ви додати примітку про колонки? У тому, що після кожної літери жодна двокрапка не означає аргу, одна двокрапка означає аргумент, а дві двокрапки означає необов'язковий арг?
limasxgoesto0

3
@WillBarnwell слід зазначити, що він був доданий через 3 роки після того, як було задано питання, тоді як головний відповідь був доданий в той же день.
rbennell

47

getopt - твій друг .. простий приклад:

function f () {
TEMP=`getopt --long -o "u:h:" "$@"`
eval set -- "$TEMP"
while true ; do
    case "$1" in
        -u )
            user=$2
            shift 2
        ;;
        -h )
            host=$2
            shift 2
        ;;
        *)
            break
        ;;
    esac 
done;

echo "user = $user, host = $host"
}

f -u myself -h some_host

У вашому / usr / bin каталозі повинні бути різні приклади.


3
Більш обширний приклад можна знайти в каталозі /usr/share/doc/util-linux/examples, принаймні, на машинах Ubuntu.
Серж Стротобанд

10

Я думаю, що це послужить більш простим прикладом того, чого ви хочете досягти. Немає необхідності використовувати зовнішні інструменти. Вбудований інструмент Bash може зробити роботу за вас.

function DOSOMETHING {

   while test $# -gt 0; do
           case "$1" in
                -first)
                    shift
                    first_argument=$1
                    shift
                    ;;
                -last)
                    shift
                    last_argument=$1
                    shift
                    ;;
                *)
                   echo "$1 is not a recognized flag!"
                   return 1;
                   ;;
          esac
  done  

  echo "First argument : $first_argument";
  echo "Last argument : $last_argument";
 }

Це дозволить вам використовувати прапори, тому незалежно від того, в якому порядку ви переходите параметри, ви отримаєте належну поведінку.

Приклад:

 DOSOMETHING -last "Adios" -first "Hola"

Вихід:

 First argument : Hola
 Last argument : Adios

Ви можете додати цю функцію до свого профілю або помістити її всередині сценарію.

Дякую!

Редагувати: Збережіть цей файл як файл, а потім виконайте його як yourfile.sh -last "Adios" -first "Hola"

#!/bin/bash
while test $# -gt 0; do
           case "$1" in
                -first)
                    shift
                    first_argument=$1
                    shift
                    ;;
                -last)
                    shift
                    last_argument=$1
                    shift
                    ;;
                *)
                   echo "$1 is not a recognized flag!"
                   return 1;
                   ;;
          esac
  done  

  echo "First argument : $first_argument";
  echo "Last argument : $last_argument";

Я використовую наведений вище код, а під час запуску він нічого не друкує. ./hello.sh DOSOMETHING -last "Adios" -first "Hola"
dinu0101

@ dinu0101 Це функція. Не сценарій. Ви повинні використовувати його як ДОЗОМЕТРЯВАННЯ "останній" Адіос "-перший" Хола "
Matias Barrios

Дякую @Matias. Зрозумів. Як запустити всередині скрипту.
dinu0101

1
Дуже дякую @Matias
dinu0101

2
Використання return 1;з останнім прикладом виходів can only 'return' from a function or sourced scriptна macOS. exit 1;Хоча перехід на роботу, як очікувалося.
Маттіас

5

Іншою альтернативою було б використовувати щось на зразок наведеного нижче прикладу, який дозволив би використовувати теги long --image або short -i, а також дозволити складені -i = "example.jpg" або окремі -i example.jpg методи передачі аргументів .

# declaring a couple of associative arrays
declare -A arguments=();  
declare -A variables=();

# declaring an index integer
declare -i index=1;

# 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";

# $@ 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

  # 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

  index=index+1;
done;

# then you could simply use the variables like so:
echo "$git_user";

3

Мені подобається найкраща відповідь Роберта Мак-Махана, оскільки, як видається, найлегше зробити так, щоб вони включали файли для будь-якого зі своїх сценаріїв. Але, схоже, є недолік у рядку, що if [[ -n ${variables[$argument_label]} ]]перекидає повідомлення, "змінних: підпис індексу". У мене немає респ коментувати, і я сумніваюся , що це правильна «виправити» , але упаковка , що ifв if [[ -n $argument_label ]] ; thenочищає його.

Ось код, який я закінчив, якщо ви знаєте кращий спосіб, будь ласка, додайте коментар до відповіді Роберта.

Включити файл "flags-declares.sh"

# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();

# declaring an index integer
declare -i index=1;

Включити файл "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;

Ваш "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";

3

Якщо ви знайомі з аргументом Python, і ви не заперечуєте закликати python для розбору аргументів bash, я знайшов фрагмент коду, який я вважав дуже корисним і дуже простим у використанні під назвою argparse-bash https://github.com/nhoffman/ арґпарш-баш

Приклад взяти зі свого скрипта example.sh:

#!/bin/bash

source $(dirname $0)/argparse.bash || exit 1
argparse "$@" <<EOF || exit 1
parser.add_argument('infile')
parser.add_argument('outfile')
parser.add_argument('-a', '--the-answer', default=42, type=int,
                    help='Pick a number [default %(default)s]')
parser.add_argument('-d', '--do-the-thing', action='store_true',
                    default=False, help='store a boolean [default %(default)s]')
parser.add_argument('-m', '--multiple', nargs='+',
                    help='multiple values allowed')
EOF

echo required infile: "$INFILE"
echo required outfile: "$OUTFILE"
echo the answer: "$THE_ANSWER"
echo -n do the thing?
if [[ $DO_THE_THING ]]; then
    echo " yes, do it"
else
    echo " no, do not do it"
fi
echo -n "arg with multiple values: "
for a in "${MULTIPLE[@]}"; do
    echo -n "[$a] "
done
echo

2

Я пропоную простий TLDR:; приклад для неініційованих.

Створіть bash-скрипт під назвою helloworld.sh

#!/bin/bash

while getopts "n:" arg; do
  case $arg in
    n) Name=$OPTARG;;
  esac
done

echo "Hello $Name!"

Потім ви можете передавати необов'язковий параметр -nпід час виконання сценарію.

Виконайте сценарій як такий:

$ bash helloworld.sh -n 'World'

Вихідні дані

$ Hello World!

Примітки

Якщо ви хочете використовувати декілька параметрів:

  1. розширити за while getops "n:" arg: doдопомогою інших параметрів, таких як while getops "n:o:p:" arg: do
  2. розширити перемикач корпусу за допомогою додаткових змінних призначень. Такі як o) Option=$OPTARGіp) Parameter=$OPTARG

1
#!/bin/bash

if getopts "n:" arg; then
  echo "Welcome $OPTARG"
fi

Збережіть його як sample.sh і спробуйте запустити

sh sample.sh -n John

у своєму терміналі.


1

У мене виникли проблеми з використанням getopts з декількома прапорами, тому я написав цей код. Він використовує модальну змінну для виявлення прапорів і використовує ці прапори для призначення аргументів змінним.

Зауважте, що якщо у прапора не повинно бути аргументу, можна зробити щось інше, ніж встановити CURRENTFLAG.

    for MYFIELD in "$@"; do

        CHECKFIRST=`echo $MYFIELD | cut -c1`

        if [ "$CHECKFIRST" == "-" ]; then
            mode="flag"
        else
            mode="arg"
        fi

        if [ "$mode" == "flag" ]; then
            case $MYFIELD in
                -a)
                    CURRENTFLAG="VARIABLE_A"
                    ;;
                -b)
                    CURRENTFLAG="VARIABLE_B"
                    ;;
                -c)
                    CURRENTFLAG="VARIABLE_C"
                    ;;
            esac
        elif [ "$mode" == "arg" ]; then
            case $CURRENTFLAG in
                VARIABLE_A)
                    VARIABLE_A="$MYFIELD"
                    ;;
                VARIABLE_B)
                    VARIABLE_B="$MYFIELD"
                    ;;
                VARIABLE_C)
                    VARIABLE_C="$MYFIELD"
                    ;;
            esac
        fi
    done

0

Тож ось це моє рішення. Я хотів би мати можливість обробляти булеві прапори без дефісу, з одним дефісом та двома дефісами, а також присвоєння параметра / значення одному та двом дефісам.

# Handle multiple types of arguments and prints some variables
#
# Boolean flags
# 1) No hyphen
#    create   Assigns `true` to the variable `CREATE`.
#             Default is `CREATE_DEFAULT`.
#    delete   Assigns true to the variable `DELETE`.
#             Default is `DELETE_DEFAULT`.
# 2) One hyphen
#      a      Assigns `true` to a. Default is `false`.
#      b      Assigns `true` to b. Default is `false`.
# 3) Two hyphens
#    cats     Assigns `true` to `cats`. By default is not set.
#    dogs     Assigns `true` to `cats`. By default is not set.
#
# Parameter - Value
# 1) One hyphen
#      c      Assign any value you want
#      d      Assign any value you want
#
# 2) Two hyphens
#   ... Anything really, whatever two-hyphen argument is given that is not
#       defined as flag, will be defined with the next argument after it.
#
# Example:
# ./parser_example.sh delete -a -c VA_1 --cats --dir /path/to/dir
parser() {
    # Define arguments with one hyphen that are boolean flags
    HYPHEN_FLAGS="a b"
    # Define arguments with two hyphens that are boolean flags
    DHYPHEN_FLAGS="cats dogs"

    # Iterate over all the arguments
    while [ $# -gt 0 ]; do
        # Handle the arguments with no hyphen
        if [[ $1 != "-"* ]]; then
            echo "Argument with no hyphen!"
            echo $1
            # Assign true to argument $1
            declare $1=true
            # Shift arguments by one to the left
            shift
        # Handle the arguments with one hyphen
        elif [[ $1 == "-"[A-Za-z0-9]* ]]; then
            # Handle the flags
            if [[ $HYPHEN_FLAGS == *"${1/-/}"* ]]; then
                echo "Argument with one hyphen flag!"
                echo $1
                # Remove the hyphen from $1
                local param="${1/-/}"
                # Assign true to $param
                declare $param=true
                # Shift by one
                shift
            # Handle the parameter-value cases
            else
                echo "Argument with one hyphen value!"
                echo $1 $2
                # Remove the hyphen from $1
                local param="${1/-/}"
                # Assign argument $2 to $param
                declare $param="$2"
                # Shift by two
                shift 2
            fi
        # Handle the arguments with two hyphens
        elif [[ $1 == "--"[A-Za-z0-9]* ]]; then
            # NOTE: For double hyphen I am using `declare -g $param`.
            #   This is the case because I am assuming that's going to be
            #   the final name of the variable
            echo "Argument with two hypens!"
            # Handle the flags
            if [[ $DHYPHEN_FLAGS == *"${1/--/}"* ]]; then
                echo $1 true
                # Remove the hyphens from $1
                local param="${1/--/}"
                # Assign argument $2 to $param
                declare -g $param=true
                # Shift by two
                shift
            # Handle the parameter-value cases
            else
                echo $1 $2
                # Remove the hyphens from $1
                local param="${1/--/}"
                # Assign argument $2 to $param
                declare -g $param="$2"
                # Shift by two
                shift 2
            fi
        fi

    done
    # Default value for arguments with no hypheb
    CREATE=${create:-'CREATE_DEFAULT'}
    DELETE=${delete:-'DELETE_DEFAULT'}
    # Default value for arguments with one hypen flag
    VAR1=${a:-false}
    VAR2=${b:-false}
    # Default value for arguments with value
    # NOTE1: This is just for illustration in one line. We can well create
    #   another function to handle this. Here I am handling the cases where
    #   we have a full named argument and a contraction of it.
    #   For example `--arg1` can be also set with `-c`.
    # NOTE2: What we are doing here is to check if $arg is defined. If not,
    #   check if $c was defined. If not, assign the default value "VD_"
    VAR3=$(if [[ $arg1 ]]; then echo $arg1; else echo ${c:-"VD_1"}; fi)
    VAR4=$(if [[ $arg2 ]]; then echo $arg2; else echo ${d:-"VD_2"}; fi)
}


# Pass all the arguments given to the script to the parser function
parser "$@"


echo $CREATE $DELETE $VAR1 $VAR2 $VAR3 $VAR4 $cats $dir

Деякі посилання

  • Основна процедура була знайдена тут .
  • Детальніше про передачу всіх аргументів функції тут .
  • Більше інформації про значення за замовчуванням тут .
  • Більше інформації про declaredo $ bash -c "help declare".
  • Більше інформації про shiftdo $ bash -c "help shift".
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.