Bracket missing error in simple bash line?

前端 未结 2 2030
清酒与你
清酒与你 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:52

    lose the []s:

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

    (added harmless newline for readability)

    you may also then want to silence the greps:

    if tail -1 /home/pi/video_buffer_usage.txt | grep -q '100% full' ||
      tail -2 "$out_file" | grep -q "$fail_str" ; then
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题