program tip

Bash 스크립트에 전달 된 인수 수 확인

radiobox 2020. 10. 2. 21:57
반응형

Bash 스크립트에 전달 된 인수 수 확인


필요한 인수 개수가 충족되지 않으면 Bash 스크립트에서 오류 메시지를 인쇄하고 싶습니다.

다음 코드를 시도했습니다.

#!/bin/bash
echo Script name: $0
echo $# arguments 
if [$# -ne 1]; 
    then echo "illegal number of parameters"
fi

알 수없는 이유로 다음과 같은 오류가 발생했습니다.

test: line 4: [2: command not found

내가 도대체 ​​뭘 잘못하고있는 겁니까?


다른 간단한 명령과 마찬가지로 [ ... ]또는 test인수 사이에 공백이 필요합니다.

if [ "$#" -ne 1 ]; then
    echo "Illegal number of parameters"
fi

또는

if test "$#" -ne 1; then
    echo "Illegal number of parameters"
fi

제안

Bash에서는 [[ ]]단어 분할 및 변수에 대한 경로 이름 확장을 수행하지 않으므로 대신 사용하는 것이 좋습니다. 따옴표는 표현식의 일부가 아닌 한 필요하지 않을 수 있습니다.

[[ $# -ne 1 ]]

또한 인용되지 않은 조건 그룹화, 패턴 일치 (와 확장 패턴 일치 extglob) 및 정규식 일치 와 같은 다른 기능도 있습니다 .

다음 예제는 인수가 유효한지 확인합니다. 하나 또는 두 개의 인수를 허용합니다.

[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]

순수한 산술 표현식의 경우, 사용하는 (( ))일부 여전히 더 좋을 수 있지만, 그들은 여전히 가능 [[ ]]처럼 그 산술 연산자와 -eq, -ne, -lt, -le, -gt, 또는 -ge단일 문자열 인수로 식을 배치하여 :

A=1
[[ 'A + 1' -eq 2 ]] && echo true  ## Prints true.

다른 기능과 결합해야하는 경우 유용합니다 [[ ]].

스크립트 종료

유효하지 않은 매개 변수가 전달 될 때 스크립트를 종료하는 것도 논리적입니다. 이것은 이미에서 제안 된 의견 으로 ekangas 하지만 누군가가 그것을 가지고이 답변을 편집 -1나뿐만 아니라 바로 그것을 할 수 있도록, 같은 반환 값.

-1Bash가 인수로 받아 들인 exit것은 명시 적으로 문서화되지 않았으며 일반적인 제안으로 사용하기에 적합하지 않습니다. 64이 정의 이후 가장 공식적인 값도 sysexits.h와 함께 #define EX_USAGE 64 /* command line usage error */. 같은 대부분의 도구 는 잘못된 인수 ls도 반환 2합니다. 나는 또한 2내 스크립트 로 돌아 왔지만 최근에는 더 이상 신경 쓰지 않고 단순히 1모든 오류에 사용 했습니다. 그러나 2가장 일반적이고 아마도 OS별로 다르기 때문에 여기에 배치 하겠습니다.

if [[ $# -ne 1 ]]; then
    echo "Illegal number of parameters"
    exit 2
fi

참고 문헌


숫자를 다루는 경우 산술 표현식 을 사용하는 것이 좋습니다 .

if (( $# != 1 )); then
    echo "Illegal number of parameters"
fi

On []: !=, =, == ... are string comparison operators and -eq, -gt ... are arithmetic binary ones.

I would use:

if [ "$#" != "1" ]; then

Or:

if [ $# -eq 1 ]; then

If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

A simple one liner that works can be done using:

[ "$#" -ne 1 ] && ( usage && exit 1 ) || main

This breaks down to:

  1. test the bash variable for size of parameters $# not equals 1 (our number of sub commands)
  2. if true then call usage() function and exit with status 1
  3. else call main() function

Thinks to note:

  • usage() can just be simple echo "$0: params"
  • main can be one long script

Check out this bash cheatsheet, it can help alot.

To check the length of arguments passed in, you use "$#"

To use the array of arguments passed in, you use "$@"

An example of checking the length, and iterating would be:

myFunc() {
  if [[ "$#" -gt 0 ]]; then
    for arg in "$@"; do
      echo $arg
    done
  fi
}

myFunc "$@"

This articled helped me, but was missing a few things for me and my situation. Hopefully this helps someone.


In case you want to be on the safe side, I recommend to use getopts.

Here is a small example:

    while getopts "x:c" opt; do
      case $opt in
        c)
          echo "-$opt was triggered, deploy to ci account" >&2
          DEPLOY_CI_ACCT="true"
          ;;
            x)
              echo "-$opt was triggered, Parameter: $OPTARG" >&2 
              CMD_TO_EXEC=${OPTARG}
              ;;
            \?)
              echo "Invalid option: -$OPTARG" >&2 
              Usage
              exit 1
              ;;
            :)
              echo "Option -$OPTARG requires an argument." >&2 
              Usage
              exit 1
              ;;
          esac
        done

see more details here for example http://wiki.bash-hackers.org/howto/getopts_tutorial


Here a simple one liners to check if only one parameter is given otherwise exit the script:

[ "$#" -ne 1 ] && echo "USAGE $0 <PARAMETER>" && exit

You should add spaces between test condition:

if [ $# -ne 1 ]; 
    then echo "illegal number of parameters"
fi

I hope this helps.

참고URL : https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script

반응형