2

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598

1 Answers1

5

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 loses 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"
Steven A. Lowe
  • 60,273
  • 18
  • 132
  • 202
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Thanks! Now first problem is clear, but none of your solutions works properly. All of them outputs "not found", while file actually present. I even shorted command to just echo command, and: `test -f ~/test111 && echo "found" || echo "not found"` works well, returns "found" `test -f "$(echo '~/test111')" && echo "found" || echo "not found"` returns "not found" Output of others is the same. If file not present - result is the same. Bash version 3.2, OS X 10.10.3 (just in case =) –  Jun 26 '15 at 11:02
  • @iMisanthrope Uhms, this must be because of the `~`, that is not expanded within double quotes. As seen in [How to manually expand a special variable (ex: ~ tilde) in bash](http://stackoverflow.com/a/3963747/1983854), you can use `$HOME` instead. – fedorqui Jun 26 '15 at 11:08
  • 1
    Yep, you right, with full path all works as should. Thanks a lot problem is solved! –  Jun 26 '15 at 11:20