2017-10-20 167 views
0

我想从没有运气的提示输入选项中分配一个变量。如果用户输入1,我想要target_db_name =“database2”。 我的代码:将变量赋值给if语句中的一个变量

while true; do 
    read -p "What is the table name?" table_name 
table_name=${table_name,,} 
    if hdfs dfs -test -e /foo/$table_name ; 
    then read -p "What is the target database you want to copy the 
“foo.${table_name}” table to? 

Your three options are: 
1) database1 
2) database2 
3) database3 

Type 1, 2, or 3: " target_db; 

(((Here is where I want to state if $target_db = "1" then target_db_name 
= "database1", if $target_db = "2" then target_db_name = "database2" etc...))) 

read -p "Would you like to begin the HDFS copy with the following configuration: 

Target Database: ${target_db_name} 
Table Name: ${table_name} 

Continue (Y/N):" 

else echo "Please provide a valid table name. 
Exiting this script" ; exit ; fi 

done 

我试图if语句,没有运气创建另一个。

"....Type 1, 2, or 3: " target_db; 
else if $target_db = "1" then target_db_name = "edw_qa_history"; fi 
+0

请显示你的尝试,所以我们可以解释你做错了什么。 – Barmar

+0

请记住'bash'中的变量赋值在'='周围没有空格。 – Barmar

+0

而且你应该使用'case'而不是'if'。 – Barmar

回答

1

if $target_db = "1" then将无法​​正常工作,因为接下来if必须是一个命令,而不是一个测试表达式。现在,在if语句中使用的最常用的命令是[(是的,这实际上是一个命令名称;它与test命令是同义的),它将测试表达式(和近括号)作为其参数并成功或失败,具体取决于是否该表达是否正确。所以,正确的语法会是这样的:

if [ "$target_db" = "1" ]; then 

注意,还有其他两个区别是什么你有:我把双引号将变量引用(几乎总是一个好主意,以避免可能解析古怪) ,并在then之前加上一个分号(需要指明[结尾和shell语法恢复的参数)。我还注意到在脚本的多行结尾处有分号;这不是必需的,行结束足以表示命令的结束。只有在同一行上有另一个命令(或类似then)时,才需要用分号作为分隔符。

但是,@Barmar在评论中指出,case可能会比这里的ifelif陈述清单更好。 case专门用于将字符串与其他字符串(或模式)进行比较,并根据匹配的字符执行不同的操作。它看起来是这样的:

case "$target_db" in 
    1) target_db_name="database1" ;; 
    2) target_db_name="database2" ;; 
    3) target_db_name="database3" ;; 
    *) "Please provide a valid table name. Exiting this script" ; exit ;; 
esac 

这里,双分号是需要,即使在行的结尾,以表示每种情况下结束。另请注意,*模式(最后一种情况)与任何内容匹配,所以它的功能类似于 ... elif ...序列中的else

最后的注意事项:使用shellcheck.net来健康检查您的代码。

+0

非常感谢您提供有用的信息 – user3508766

0

您不需要if语句将数字映射到数组;你只需要一个数组。

db_names=(
    "datebase 1" 
    "database 2" 
    "database 3" 
) 

# ... 

target_db_name=${db_names[$target_db - 1]} 
if [[ -z $target_db_name ]]; then 
    exit 
fi