我想要得到一個用戶輸入循環,直到輸入/名稱是唯一的(不包含在輸出/變量)。Bash用戶輸入,而不匹配變量循環
我一直試圖做這樣的事情,我認爲會工作:
read -p "$QlabelName" input
while [[ "$input" == "$(/usr/sbin/networksetup -listallnetworkservices |grep "$input")" ]]; do
read -p "Name already in use, please enter a unique name:" input
done
我也試圖把$(/usr/sbin/networksetup -listallnetworkservices |grep "$input")
位到一個變量本身,然後使用條件[[ "$input" == "GREPVARIABLE" ]]
沒有成功。
原始用戶輸入的菜單,沒有循環(工作):
labelName=NJDC
QlabelName=$(echo Please enter the name of connection to be displayed from within the GUI [$labelName]:)
read -p "$QlabelName" input
labelName="${input:-$labelName}"
echo "The connection name will be set to: '$labelName'"
我已經嘗試了多種解決方案,從SO,UNIX,ServerFault等,但沒有成功。我試過if
,while
,until
,!=
,==
,=~
也沒有成功。
我已經通過簡單的調試echo
確認變量包含數據,但循環不起作用。
編輯(解決方案,在上下文中的問題,感謝@ LinuxDisciple的答案):
labelName=NJDC
QlabelName=$(echo Please enter the name of connection to be displayed from within the GUI [$labelName]:)
read -p "$QlabelName" input
while /usr/sbin/networksetup -listallnetworkservices |grep -q "^${input}$"; do
read -p "Name already in use, please enter a unique name:" input
done
labelName="${input:-$labelName}"
echo "The connection name will be set to: '$labelName'"
這對我很重要,保持默認的變量值labelName
和輸出正確的信息給用戶。
我只是想你的循環的簡化版本(使用cat命令,而不是networksetup命令),並按預期工作。請張貼您的意見,預期結果和實際結果。 –
@JEarls嗯,我也試圖將'cat'命令/ grep變成一個變量。你能分享你製作它的方式嗎? – TryTryAgain
'echo'不是調試此問題的好方法,因爲您無法分辨變量是否具有會影響匹配的尾隨空格或控制字符。您可以使用'printf'%q \ n'「$ variable」'來查看一個明確的表示。 –