I have a cycle in which the input data is checked. If the data is an empty string, then exit the loop. But I do not understand how to make the correct check for an empty string. This is how it does not work:

while [[ 1 -eq 1 ]] do read nm if [[ n=="" || m=="" ]] # This is the mistake then break fi done 

In this example, the condition always works.

  • Are you passing the parameters? if [$ # -eq 0] then echo "No arguments supplied" fi - Meiram Chuzhenbayev
  • I recommend to look at this answer here: serverfault.com/a/382740 - Crystal

1 answer 1

So it should earn ( $ signs in front of the variable name):

 while true do read nm if [[ "$n" == "" || "$m" == "" ]]; then break fi done 

Quotes around $n and $m are needed in case the variable is equal to an empty string, otherwise without quotes you would have if [[ == "" || == "" ]]; then if [[ == "" || == "" ]]; then

Slightly more compact option:

 while :; do read nm [[ -z $n || -z $m ]] && break done 

Here in the while condition the command is used : which does nothing and always returns true . The condition is -z which checks the string for an empty string.

  • Yes, it really worked. The only thing, it is not clear why the spaces are necessarily needed before and after == . Without them, the condition is always satisfied. - faoxis
  • -z $n || -z $m -z $n || -z $m - PinkTux
  • @faoxis without spaces is merged into one argument for if . As if you were writing cp file1file2 instead of cp file1 file2 . - Vladimir Gamalyan
  • In a sense, in one argument? In which ? - faoxis
  • @faoxis B argument for if . - Vladimir Gamalyan