Shell脚本条件语句if else不起作用

时间:2012-05-01 19:23:28

标签: arrays macos shell if-statement

对于壳牌来说,我是一个菜鸟

这个块应该可以工作,但不是

     #!/bin/bash 
     # LOCAL CONFIGURATION SETTINGS - DB_CONFIG is a "fake" associative array
     #----------------------------------------------------------------------------------
     DB_CONFIG=(
        "DB_NAME=>"
        "DB_USER=>root"
        "DB_PASSWORD=>root"
        "DB_HOST=>127.0.0.1"
        "DB_CHARSET=>utf8"
        "DB_COLLATE=>"
     );

     for prop in ${DB_CONFIG[@]} ; do
     key=${prop%%=>*}
     value=${prop##*=>}
     echo $key;
     if[["$key" == "DB_HOST"]] then 
           db_host="$value"

     if[["$key" == "DB_PASSWORD"]] then  
           db_password="$value"

     done;


     # now set the mysql_conn string with the vars above.
     MYSQL_CON="/Applications/MAMP/Library/bin/mysql --host=$db_host -uroot -$db_password"
     exit;
     REPO='http://svn.wp-plugins.org/'

问题是如何检查条件$key == 'DB_HOST'我无法弄清楚表达式的语法。我已经研究了如何做到这一点,但是在我的mac(运行bash 3.2)上,如果抱怨语法错误。

3 个答案:

答案 0 :(得分:1)

在此之前,您需要为[]以及;留出空格

if [ "$key" == "DB_HOST" ]; then 
      db_host="$value"
fi

答案 1 :(得分:0)

这应该适合你:

DB_CONFIG=(
  "DB_NAME=>"
  "DB_USER=>root"
  "DB_PASSWORD=>root"
  "DB_HOST=>127.0.0.1"
  "DB_CHARSET=>utf8"
  "DB_COLLATE=>"
);  

for prop in ${DB_CONFIG[@]}; do
  key=${prop%%=>*}
  value=${prop##*=>}

  if [[ "$key" == "DB_HOST" ]]; then 
       db_host="$value"
  elif [[ "$key" == "DB_PASSWORD" ]]; then  
       db_password="$value"
  fi  
done

echo "$db_host" "$db_password"

您在[[之后和]]之前错过了空格。您还错过了fi,它们对应于C或Java中的闭括号,并且是bash所必需的。此外,if语句在条件测试后需要;

答案 2 :(得分:0)

这是一个很棒的bash脚本快速参考指南

http://linuxconfig.org/Bash_scripting_Tutorial