2017-10-20 163 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