我对 test
命令语法感到困惑。我的目标是检查文件是否存在,但文件路径由 sed 命令形成。
所以,我尝试,例如:
echo '~/test111' | sed s/111/222/g | test -f && echo "found" || echo "not found"
但是该命令总是返回“found”。我做错了什么?
最佳答案
按照当前的方法,您只是说:
test -f && echo "yes" || echo "no"
由于 test -f
默认返回 true,因此您总是得到“yes”:
$ test -f
$ echo $?
0
正确的语法是test -f "string"
:
所以你想说:
string=$(echo '~/test111'|sed 's/111/222/g')
test -f "$string" && echo "found" || echo "not found"
可以压缩为:
test -f "$(echo '~/test111'|sed 's/111/222/g')" && echo "found" || echo "not found"
但它失去了可读性。
您还可以使用 xargs
以上一个管道给出的名称执行给定的操作:
echo '~/test111'|sed 's/111/222/g' | xargs test -f && echo "found" || echo "not found"
关于bash - 将管道输出传递给测试命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31070041/