2017-10-13 184 views
0

以下while循環旨在不斷詢問用戶輸入,直到輸入指定的「break」字符。但是,由於某些原因,無論輸入什麼文本,都會觸發IF語句。IF語句觸發時不包含真正的語句

while true; do 
    #Prompt user for Input 
    printf "Please insert value. Insert the letter 'D' when you are done\n"; 
    #Read User Input 
    read User_Input; 
    echo "DEBUG: Input is: $User_Input"; 
    #Check User Input for Break Command 
     if [ "$User_Input"=="D" ]; then 
      break 
     fi 

done 

而且腳本中的我有用戶輸入變量至於我可以告訴if語句是正確的,該腳本不拋出任何錯誤,當運行宣佈爲User_Input="";

+0

如果您閱讀[Bash手冊頁](http://man7.org/linux/man-pages/man1/bash.1.html),您會看到'=='運算符是Bash - 用於雙括號表達式的特定擴展(即'[[...]]')。對於單支架,您應該閱讀[test'手冊頁](http://man7.org/linux/man-pages/man1/test.1.html)。 –

回答

3
if [ "$User_Input"=="D" ]; then 

DEBUG: Input is: a 
+ '[' a==D ']' 
+ break 

應該寫成

if [ "$User_Input" == "D" ]; then 

DEBUG: Input is: e 
+ '[' e == D ']' 
+ true 
+ printf 'Please insert value. Insert the letter '\''D'\'' when you are done\n' 
Please insert value. Insert the letter 'D' when you are done 
+ read User_Input 
D 
+ echo 'DEBUG: Input is: D' 
DEBUG: Input is: D 
+ '[' D == D ']' 
+ break 

空間之前,需要和後==

2

if [ "$User_Input"=="D" ]; then 

# space 
if [ "$User_Input" == "D" ]; then 

因爲它調用命令[與4參數。

由於bash buildins的手冊頁聲明:「每個運算符和操作數 必須是單獨的參數。」