2016-09-27 161 views
0

我想要得到一個用戶輸入循環,直到輸入/名稱是唯一的(不包含在輸出/變量)。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和輸出正確的信息給用戶。

+0

我只是想你的循環的簡化版本(使用cat命令,而不是networksetup命令),並按預期工作。請張貼您的意見,預期結果和實際結果。 –

+0

@JEarls嗯,我也試圖將'cat'命令/ grep變成一個變量。你能分享你製作它的方式嗎? – TryTryAgain

+0

'echo'不是調試此問題的好方法,因爲您無法分辨變量是否具有會影響匹配的尾隨空格或控制字符。您可以使用'printf'%q \ n'「$ variable」'來查看一個明確的表示。 –

回答

1
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 

grep的返回碼是while不夠好,因爲我們不想竟看到輸出,我們可以使用-q壓制它。您也可以在不使用-q的情況下運行它,查看grep實際找到的內容,直到您確信它正確運行。

爲了進一步的可調試性,我將管道輸出到cat -A。您可以在while循環呼應的變量值,只是在done之後添加|cat -A立即,它應該顯示所有字符:

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 
    echo "Input was:'$input'" 
done |cat -A 
+0

用'grep -q「直接運行蝙蝠^ $ {input} $」'建議,非常好!非常感謝!另外,到'cat -A'的管道是一個有用的提示,請再次感謝。 – TryTryAgain