Skip to content
Advertisement

Until Loop not working as expected

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…

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement