Trouble reading input inside bash while loop
Hi all , its been a while since I wrote a bash script but I've run into some trouble in the while clause. The answer reads in fine but it doesn't register that a valid answer has been entered and just assumes that every answer entered is invalid.
I think it has to do with how Im doing on the comparisons , if anyone could provide any insight as to why this is not working I would appreciate it. Code:
#!/bin/bash Would you like to move 119305-GlassMaxX.tar.gz to External HDD? Y/N Y Answer must be of the form Y or N Would you like to move 119305-GlassMaxX.tar.gz to External HDD? Y/N Answer is Y N Answer must be of the form Y or N Would you like to move 119305-GlassMaxX.tar.gz to External HDD? Y/N Answer is N Y Answer must be of the form Y or N Would you like to move 119305-GlassMaxX.tar.gz to External HDD? Y/N Answer is Y HJHJ Answer must be of the form Y or N Would you like to move 119305-GlassMaxX.tar.gz to External HDD? Y/N Answer is HJHJ |
Well, you are looping on the condition that $answer is either unlike Y or unlike N. Since it can't be both Y and N at the same time, the while loop continues indefinitely.
Also, the single quotes prevent shell expansion of the variable, so you're comparing the literal string $answer rather than the contents of the variable. How about: while [ "$answer" != "Y" ] && [ "$answer" != "N" ] |
Thanks Ser Olmy, that did the trick, it works fine now. I appreciate it.
|
Maybe it can also be phrased as a regex and avoid an external program to be called:
Code:
while ! [[ "$answer" =~ ^[NY]$ ]]; do |
Or if looking for the negative maybe use an 'until' loop.
|
Checking user input is more traditionally done with a case statement, and embedding it in a continuous loop will make it repeat until you get the correct answer and manually break out of it.
Code:
while true; do Second, parsing ls for filenames is not a good idea, particularly in a for loop. Just use shell globbing. Code:
for f in "$HOME/Downloads/"* ; do |
All times are GMT -5. The time now is 12:35 AM. |