1

I have the following simple bash script:

for VAR
do
   echo file found $VAR
done

what I want is for it to print all the files that contain the extension .png. I would expect the following command line to work, but it does not. Why?

ls *.png | myscript.sh

or

./myscript.sh < `ls *.png`
3
  • Looping on the contents of a variable is not the same as piping the results of a command to another command. The results of ls will be available to myscript.sh as its standard input, not as a variable. Commented Mar 7, 2012 at 18:37
  • how would you modify my script to loop the standard input? Commented Mar 7, 2012 at 18:44
  • Second calling syntax is wrong: it redirects content of the first file found to your script. Commented Mar 7, 2012 at 18:48

2 Answers 2

3

You need xargs:

ls *.png | xargs myscript.sh

Sign up to request clarification or add additional context in comments.

4 Comments

your command does not work for me. Am I missing something here?
try [..] |xargs ./myscript.sh, if the scritpt is not in your PATH.
This works because xargs passes its stdin to the given command as command line parameters.
The non-obvious part for me was parsing of arguments with "for".
3

To read standard input script should look like:

while read line; do
  echo file found $line
done

1 Comment

Edited to remove the parentheses: original answer won't work because the parentheses will cause the read command to occur in a subshell, thus the variable will disappear when the subshell exits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.