programing

인수가 이 문자열과 같으면 이 문자열과 같은 변수를 정의합니다.

javajsp 2023. 4. 9. 20:56

인수가 이 문자열과 같으면 이 문자열과 같은 변수를 정의합니다.

bash 스크립트를 실행하고 있는데 변수 콜이 하나 왔어요.source1개의 어레이는samples, 다음과 같이 합니다.

source='country'
samples=(US Canada Mexico...)

소스 수를 확장하고 싶기 때문에(각 소스에는 자체 샘플이 있습니다), 이를 위해 몇 가지 인수를 추가하려고 했습니다.이거 해봤어요.

source=""
samples=("")
if [ $1="country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
   echo "try again"
fi

제가 대본을 돌려봤을 때source countries.sh country효과가 없었어요내가 뭘 잘못하고 있지?

공백도 잊지 마세요.

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

다음 중 하나를 사용할 수 있습니다.=" 또는==bash 문자열 비교 연산자.중요한 것은 괄호 안의 간격입니다.적절한 방법은 괄호 안에 간격을 두고 연산자를 둘레에 간격을 두는 것입니다.경우에 따라서는 다른 조합이 동작하는 경우도 있습니다만, 다음의 조합은 범용적인 예가 됩니다.

if [ "$1" == "something" ]; then     ## GOOD

if [ "$1" = "something" ]; then      ## GOOD

if [ "$1"="something" ]; then        ## BAD (operator spacing)

if ["$1" == "something"]; then       ## BAD (bracket spacing)

또한 이중 괄호는 단일 괄호와 비교하여 약간 다르게 취급됩니다.

if [[ $a == z* ]]; then   # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).

if [ $a == z* ]; then     # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).

명령줄 인수를 bash 스크립트로 해석하려고 하는 것 같습니다.저는 최근에 이것을 직접 찾아봤어요.다음과 같은 것을 알게 되었습니다.인수의 해석에 도움이 될 것 같습니다.

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

아래의 스니펫을 tl;dr로 추가했습니다.

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

언급URL : https://stackoverflow.com/questions/9727695/if-arguments-is-equal-to-this-string-define-a-variable-like-this-string