Bash 脚本缺少“]”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15993062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:35:12  来源:igfitidea点击:

Bash scripting missing ']'

bashscripting

提问by quick-

I am getting an error ./test.sh: line 13: [: missing `]' in the file test.sh I tried using brackets and other options such as -a or by checking the size of the file p1 but the error is always there and the else statement is always executed irrespective of the input given.I even tried by removing the ; in line 13 but it didn't help.

我收到错误 ./test.sh: line 13: [: missing `]' in the file test.sh 我尝试使用方括号和其他选项,例如 -a 或检查文件 p1 的大小,但错误是总是在那里,无论给定的输入如何,总是执行 else 语句。我什至尝试删除 ; 在第 13 行,但没有帮助。

test.sh

测试文件

#!/bin/bash
echo "Enter app name"
read y
$y &
top -b -n 1 > topLog.log
#-w checks for the whole word not and sub string from that word
grep -w "$y" topLog.log > p1
#-s option checks if the file p1 is present or not
if [ -s "p1"];  #line 13
then 
    echo "Successful "
else
    echo "Unsuccessful"
fi
rm p1

I am new to bash scripting.So if there is any silly mistake please excuse me.

我是 bash 脚本的新手。所以如果有任何愚蠢的错误,请原谅。

回答by Fredrik Pihl

Change

改变

if [ -s "p1"];  #line 13

into

进入

if [ -s "p1" ];  #line 13

note the space.

注意空间。

回答by Carl G

I got this error while trying to use the &&operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

我在尝试&&在像[ ... && ... ]. 我不得不切换到[[ ... && ... ]].

回答by Elmar Peise

You're missing a space after "p1":

您在以下之后缺少一个空格"p1"

if [ -s "p1" ];

回答by Sam Ruby

add a space before the close bracket

在右括号前添加一个空格

回答by vasu

if [ -s "p1" ];

如果 [ -s "p1" ];

mind the space :P

注意空间:P

回答by Vladimir Marton

If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unixon linux machine and run dos2unix yourscript.sh. Then, run the script.

如果您在 Windows 上创建了脚本并希望在 linux 机器上运行它,并且您确定代码中没有错误,请在 linux 机器上安装dos2unix并运行dos2unix yourscript.sh. 然后,运行脚本。