Bash error on if statement -


i have error in bash script when if control between string , script read function

 #! /bin/bash  test1="false" while [ $test1 == "false" ]; tail -1 demo.txt | while read test echo $test done if [ "test" == $test  ];         test1="true"         echo "end" else         test1="true"         echo "else"  fi done 

this code , result:

    #! /bin/bash  test1="false" while [ $test1 == "false" ]; tail -1 demo.txt | while read test echo $test done if [ "test1" == "$test"  ];         test1="true"         echo "end" else         test1="true"         echo "else"  fi done  "test2.sh" 17 lines, 215 characters xxx@xxx:/tmp $ ./test2.sh test1 else 

if $test empty, if becomes:

if [ "test" ==   ]; 

which raises error:

-bash: [: test: unary operator expected 

you need enclose variable in quotes in order there value when $test empty:

if [ "test" == "$test"  ]; 

edit: there 2 reasons why $test "empty". first reason because | creates subprocess, biffen correctly states. when subprocess exits, variables set within go away. in case, it's not $test empty; doesn't exist. not @ time try use in if.

if avoid subprocess (which can done in several ways), might still have empty $test. trivial way avoid write not pipe, process redirect:

while read test     echo $test done < <(tail -1 demo.txt) 

this set local variable test first line, display it, set next line, there no next line; read fails, not before nukes $test (so $test ends empty). works say, can check running this:

while read test     realtest="$test"     echo $test done < <(tail -1 demo.txt)  echo realtest: $realtest 

and see $realtest have last line of file (it not have, if tried redirection approach).

however, if want read single line, why while loop?

read test < <(tail -1 demo.txt) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -