
我正在編寫一個 bash 腳本來處理來自 html 表單的輸入。
第一個問題是,在使用指令作為條件時,我無法讓 if 語句運作。我正在嘗試檢查中間名首字母的用戶輸入並調整它以確保它可以合併到 $answer 中。
這是它應該如何處理的範例。
使用者從html表單輸入三個不同的欄位;名字、中間名首字母、姓氏。
名字:喬治
中間首字母:W.
姓氏:布希
Shell 腳本將處理並比較使用者輸入和實際答案。實際答案是“喬治·W·布希”
使用者輸入:
George W. Bush = 正確 echo“你是對的!”
喬治·W·布希 = 通過在“W”後自動添加句點來正確
喬治·布希 != 錯誤並回顯“沒有中間首字母!”
Geor W. Bus != 錯誤並回顯“名字和姓氏錯誤!”
#! /bin/bash
echo Content-type: "text/html"
echo ""
read input #name variable $first, $middle, $last name
first=`user input`
middle=`user input`
last=`user input`
president=`actual answer, full name of president`
answer=`user answer, combination of $first, $middle, $last`
correctF=`actual first name from $president`
correctM=`actual middle initial from $president`
correctL=`actual last name from $president`
#cut by column from $president
第一個問題從這裡開始。
if [[ $(echo $middle | wc -l) = 1 ]] ; then
middle=`echo "$middle""."`
#check if middle initial variable was entered with just the letter and place a period after
elif [[ $(echo $middle | grep '.') = 'true' ]] ; then
middle=`echo "$middle"`
#check if middle initial variable was entered with the period and leave it as is
else
middle=`'false'`
#no middle initial variable was entered and is null
fi
while 迴圈與 if 語句的第二個問題。
我試著將使用者輸入 $answer 與實際答案 $president 進行比較,並回顯 $answer 出了什麼問題。本節沒有任何內容回顯。
while [ "$president" -ne "$answer" ] #not working
do
if [ "$first" -ne "$correctF" ]
then
echo "Wrong first name!"
elif [ "$middle" -ne "$correctM" ]
then
echo "Wrong middle initial!"
elif [ "$last" -ne "$correctL" ]
then
echo "Wrong last name!"
elif [ -z "$middle" -ne "$correctM" ]
then
echo "No middle initial!"
elif [ "$first" -ne "$correctF" ] && [ "$last" -ne "$correctL" ]
then
echo "Wrong first and last name!"
elif [ "$first" -ne "$correctF" ] && [ "$middle" -ne "$correctM" ]
then
echo "Wrong first name and middle initial!"
elif [ "$middle" -ne "$correctM" ] && [ "$last" -ne "$correctL" ]
then
echo "Wrong middle initial and last name!"
elif [ "$first" -ne "$correctF" ] && [ "$middle" -ne "$correctM"] && [ "$last" -ne "$correctL" ]
then
echo "You got it all wrong!"
else
echo "You are correct!"
fi
我需要將命令正確地實現到 if 語句條件中,並編寫具有多個條件的 if 語句。
答案1
cas 說,「這個腳本有太多錯誤,我甚至不知道從哪裡開始…」。好吧,我有一些關於從哪裡開始的想法:
- 請不要要求我們調試您的腳本然後發布偽代碼。您的第一個程式碼區塊在不起作用的地方包含反引號 (`)。
- 請說得更明確一點。 「我無法讓我的 if 語句發揮作用」對我們來說沒有多大幫助。會發生什麼事?
- 您應該始終引用您的 shell 變數引用(例如,
"$middle"
),除非您有充分的理由不這樣做,並且您確定您知道自己在做什麼。 $(echo "$middle" | grep '.')
'true'
僅當"$middle"
等於時才等於true
。的輸出grep
是內容輸入中與作為參數給出的模式匹配的行的數量。.
是一個表示“任何字元”的模式,因此grep '.'
將匹配任何非空白輸入行。檢查實際週期(.
), 使用grep '\.'
。請注意,這W.
不僅會匹配.W
,...
,3.14159
等。- 為什麼要做一個
while
?您是否希望該程式碼執行多次?您是否期望對相同資料重複執行時會得到不同的結果?循環的終點在哪裡? -eq
和-ne
僅應在比較整數時使用;使用=
和!=
對於字串。- 你是什麼意思?
-z STRING1 -ne STRING2
也許還有其他問題,但我的眼睛太痛了,無法再看這個了。