Programming

올바른 개수의 인수 확인

procodes 2020. 7. 3. 22:17
반응형

올바른 개수의 인수 확인


올바른 개수의 인수 (한 개의 인수)를 확인하는 방법 누군가가 올바른 수의 인수를 전달하지 않고 스크립트를 호출하려고 시도하고 명령 행 인수가 실제로 존재하며 디렉토리인지 확인합니다.


#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

변환 : 인수 수가 (숫자 적으로) 1이 아니거나 첫 번째 인수가 디렉토리가 아닌 경우 stderr에 사용법을 출력하고 실패 상태 코드로 종료하십시오.

보다 친숙한 오류보고 :

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

고양이 script.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

아래와 같이 실행하십시오-

./script.sh directory1 directory2

출력은 다음과 같습니다-

directory1 exit
directory2 Does not exists

" $#"를 사용 하여 명령 행에 전달 된 총 인수 수를 확인할 수 있습니다. 예를 들어 내 쉘 스크립트 이름은 다음과 같습니다.hello.sh

sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument 
if [ $# -eq 1 ] 
then
    echo $1
else
    echo "invalid argument please pass only one argument "
fi

출력은 hello-world

참고 URL : https://stackoverflow.com/questions/4341630/checking-for-the-correct-number-of-arguments

반응형