나는 bash 스크립트를하고 있으며 이제 다음과 같이 하나의 변수 호출 source과 하나의 배열 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 테스트 -r 서버 -p 비밀번호 -v
