Reputation: 7820
I'm trying to get a user input to loop until the input/name is unique (not contained in output/variable).
I've tried to do something like this, which I thought would have worked:
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
I've also tried putting the $(/usr/sbin/networksetup -listallnetworkservices |grep "$input")
bit into a variable itself and then using the condition [[ "$input" == "GREPVARIABLE" ]]
without success.
Original user input menu, without loop (working):
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'"
I've tried a variety of solutions from SO, Unix, ServerFault, etc with no success. I've tried if
, while
, until
, !=
, ==
, =~
as well with no success.
I've confirmed with simple debug echo
's at each step that variables contain the data, but the loop is not working.
EDIT (solution, in context to the question, thanks to @LinuxDisciple's answer):
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'"
This was important to me to keep default variable values for labelName
and output the correct information to the user.
Upvotes: 0
Views: 301
Reputation: 2379
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
's return code is good enough for while
, and since we don't want to actually see the output, we can use -q
to suppress it. You can also run it without -q
to see what grep actually found until you're satisfied that it's running correctly.
For further debuggability, I would pipe the output to cat -A
. You can echo your variable value in the while-loop and just add |cat -A
immediately after the done
and it should show all the characters:
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
Upvotes: 1