![](/img/trans.png)
[英]How can I test a command before a pipe, capture it's output and understand if the command ran successfully or not
[英]Passing pipe output to Test command
我對test
命令語法感到困惑。 我的目標是檢查文件是否存在,但由sed
命令形成的文件路徑。
所以,我嘗試,例如:
echo '~/test111' | sed s/111/222/g | test -f && echo "found" || echo "not found"
但該命令總是返回“找到”。 我究竟做錯了什么?
使用當前的方法,您只是說:
test -f && echo "yes" || echo "no"
由於test -f
默認返回 true,因此您總是得到“是”:
$ 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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.