Bracket missing error in simple bash line?

前端 未结 2 2035
清酒与你
清酒与你 2021-01-29 03:11

The following 2 lines in my bash script:

fail_str=$\'Checking...\\nChecking...\'
if [ tail -1 /home/pi/video_buffer_usage.txt | grep \'100% full\' ] || [ tail -2         


        
2条回答
  •  抹茶落季
    2021-01-29 03:57

    An if condition is a command, which is taken to mean "true" if it returns 0 and "false" otherwise.

    In your case, that command is :

    [ tail -1 /home/pi/video_buffer_usage.txt | grep '100% full' ] || [ tail -2 $out_file | grep "$fail_str" ]
    

    For now, let us focus on the first part :

    [ tail -1 /home/pi/video_buffer_usage.txt | grep '100% full' ]
    

    The opening bracket is a command (a built-in in Bash). This command reads the arguments it is provided with, and expects one last argument, a closing bracket. Now, you may think "hey, I did provide a closing bracket". But you need to look at the command like Bash looks at it.

    Bash looks at the whole command, sees the pipe symbol, and concludes you want to create a pipeline made of two commands. The opening and closing brackets are not part of the same simple command. This is what Bash sees :

    { [ tail -1 /home/pi/video_buffer_usage.txt ; } | { grep '100% full' ] `}
    

    This is why Bash complains of a missing closing bracket.

    You cannot put pipelines inside a test statement. You can store the string you want to test inside a variable (e.g. with a command substitution $()) and then test the string, or you can remove the brackets and use the command alone if its return status does the job, as suggested in @webb's answer. But you cannot use a pipeline inside the brackets.

提交回复
热议问题