Understanding linux arguments and piping

So I am trying to use sh (Bourne Shell) to write some scripts. I continue to face this confusion. For the following:

1. rm `echo test`
2. echo test | rm

      

I know backticks are used to run a command first, okay. But for the pipeline at # 2, why doesn't rm take as an argument? Is there something about pipelines that I don't understand? I thought it was just sending the output of one command as input to another.

And ... maybe related to my confusion.

dir=/blah/blar/blar
files=`ls ${dir} -rt`
count=`wc -l $files` # doesn't work, in fact it running it along with each file that exists
count2=`$files | wc -l` # doesn't work

      

Why can't I save ls to "files" and use that?

+3


source to share


2 answers


You will need to use xargs

there since it rm

takes arguments to remove, it doesn't read from STDIN

(this is what channels usually broadcast).

echo test | xargs rm

      

The first one works because backlinks for replacements are like ${}

, but not so easy. :)



Alternatively, you can use find

.

find . -name test -exec rm -f '{}' \;

      

+5


source


In the first case, the results echo test

(string test

) are provided as a command line argument for rm

. In the second, the line test

is passed to a file descriptor stdin

in rm

. These are two different things. Since rm doesn't read from stdin, it never sees test

.



+1


source







All Articles