Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash shell中的条件检查_Bash_Shell_Exit Code - Fatal编程技术网

Bash shell中的条件检查

Bash shell中的条件检查,bash,shell,exit-code,Bash,Shell,Exit Code,我有一个python脚本p.py,它对一些文件执行exit(“ABC”)。我想编写一个Ubuntu shell,将脚本退出(“ABC”)的文件复制到一个文件夹中: #!/bin/bash FILES=*.txt TOOL=p.py TAREGT=../TARGET/ for f in $FILES do if [ $(python $TOOL $f) = "ABC" ] then echo "$f" cp $f $TARGET fi d

我有一个python脚本
p.py
,它对一些文件执行
exit(“ABC”)
。我想编写一个Ubuntu shell,将脚本退出(“ABC”)的文件复制到一个文件夹中:

#!/bin/bash

FILES=*.txt
TOOL=p.py
TAREGT=../TARGET/

for f in $FILES
do
    if [ $(python $TOOL $f) = "ABC" ]
    then
        echo "$f"
        cp $f $TARGET
    fi
done

但是条件检查
如果[$(python$TOOL$f)=“ABC”]
似乎不起作用,它会显示
/filter.sh:line 13:[:=:预期的一元运算符
。有人能告诉我出了什么问题吗?

退出()的参数是python脚本返回的(成功/错误)。(python的
退出()的参数)
。请注意
退出(“ABC”)
如何不返回
“ABC”
,而是将其打印到
stderr
并返回
1

返回代码是在调用shell的
$?
变量中结束的代码,或者您要测试的代码,如下所示:

# Successful if return code zero, failure otherwise.
# (This is somewhat bass-ackwards when compared to C/C++/Java "if".)
if python $TOOL $f
then
    ...
fi
$(…)
构造被替换为被调用脚本/可执行文件的输出,这完全是另一回事

如果你在比较字符串,你必须引用它们

if [ "$(python $TOOL $f)" = "ABC" ]
或者使用bash改进的测试
[[

if [[ $(python $TOOL $f) = "ABC" ]]

谢谢,但是在我的
p.py
中,有几种退出方式:
exit(“ABC”)
exit(“DEF”)
,等等。我如何在shell中检查不同的可能性?@SoftTimur:最好参考您正在使用的函数的类型。任何非零/非空参数都可以用于
exit()
表示您的脚本对任何调用方都失败。我严重怀疑这是您正在寻找的,因此您的脚本应该打印其结果以输出并成功退出(即,
exit(0)
)。@SoftTimur尤其是,您的退出代码应该是介于0和255之间的整数值(或者-128到127,这取决于您是将其视为有符号的还是无符号的-但它应该是一个单字节值)…@twalberg:不一定;Python为
exit()添加了额外的功能
这使得SoftTimur的代码完全有效:文本被打印到
stderr
,脚本以返回代码1终止。@DevSolar Python可能允许这样做,但就shell脚本包装而言,任何进程(无论是Python、Perl、Ada还是Cobol)的退出代码都是单字节整数。这是一个“bash”脚本,而不是“Ubuntu”脚本。无论您是在Ubuntu、AIX还是Cygwin上运行,都没有什么区别。(同样,无论您在哪里运行它,它都是“Python”脚本。)