Passing pipe output to Test command

时间:2015-06-26 09:49:28

标签: bash if-statement sed echo test-command

I'm confused with test command syntax. My goal is to check if file exists, but file path formed by sed command.

So, I try, for example:

echo '~/test111' | sed s/111/222/g | test -f && echo "found" || echo "not found"

But that command always returns "found". What am I doing wrong?

1 个答案:

答案 0 :(得分:3)

With the currenty approach, you are just saying:

test -f && echo "yes" || echo "no"

Since test -f returns true as default, you are always getting "yes":

$ test -f
$ echo $?
0

The correct syntax is test -f "string":

So you want to say:

string=$(echo '~/test111'|sed 's/111/222/g')
test -f "$string" && echo "found" || echo "not found"

Which can be compacted into:

test -f "$(echo '~/test111'|sed 's/111/222/g')" && echo "found" || echo "not found"

but it looses readability.

And also you can use xargs to perform the given action in the name given by the previous pipe:

echo '~/test111'|sed 's/111/222/g' | xargs test -f && echo "found" || echo "not found"