Reputation: 3
I'm currently learning Linux and as an homework, we have to create a few basic shell scripts. Nothing especially complicated but this one is giving me headaches. Here's my code :
until [ "$toPrint" == 'fin' ]
do
echo "Enter file name to print out :" ; read toPrint
sh ./afficher.sh "$toPrint"
done
Basically, I have another script called afficher.sh (I'm french so don't mind the french language used) and it reads whatever file name it gets as a parameter. However, the moment I type "fin", everything is supposed to stop except it still tries to print the file called "fin". I read a bit about the until loop on Internet and once it becomes True, it should stop, which is not my case...
Upvotes: 0
Views: 744
Reputation: 295520
Personally, I'd implement this like so -- with a while
loop, not an until
loop, and checking for the exit condition separately and explicitly:
while true; do
echo "Enter file name to print out :" ; read toPrint
[ "$toPrint" = fin ] && break
sh ./afficher.sh "$toPrint"
done
If you really want to use the loop's condition, you can do that:
while echo "Enter file name to print out :";
read toPrint &&
[ "$toPrint" != fin ]; do
sh ./afficher.sh "$toPrint"
done
...but personally, I'm less fond of this on aesthetic grounds.
Upvotes: 1
Reputation: 14510
You check the condition at the top of the loop, but you enter the value in the middle of the loop. The next thing you do after reading the value is always pass it to afficher.sh
and then once that is done you check its value to see if you should stop. If you don't want to run afficher.sh
on the fin
value, you'll need to make sure your control flow allows you to do the comparison before you invoke afficher.sh
.
Upvotes: 1