2

Here is what i want to do... I want to write a script which sends all the files in a folder as an input to the command2.

I know pipes are used to send the output of one command to another but in my case, when i do

ls | command

What this does is it sends the output of ls ( i.e. all the files in the folder ) as a single input. Instead, I want that the individual files are sent as an argument to the command2, one by one.

Can anyone please help me out i really searched a lot for it but didn't find much.

Chintan Mehta
  • 129
  • 1
  • 9
  • 1
    https://stackoverflow.com/questions/3886295/how-do-i-list-one-filename-per-output-line-in-linux would that help? – Sonamor Apr 09 '18 at 16:29
  • Chances are that `find` or a loop of files in your directory will do a better job of whatever you are trying to do. It's [generally considered a bad idea to parse the output](https://unix.stackexchange.com/questions/128985/why-not-parse-ls) of `ls` – JNevill Apr 09 '18 at 16:30
  • In this particular case, of course, simply `command *` is superior, and avoids [parsing `ls` output](https://mywiki.wooledge.org/ParsingLs) – tripleee Apr 09 '18 at 17:02
  • @Sonamor : I understood the question in that the OP want to invoke *command* many times, once for each input file. – user1934428 Apr 10 '18 at 05:44
  • @ChintanMehta: How about `echo *|xargs -n 1 your_command` ? Note that in this case, *your_command* doesn't get the (single) filename via stdin, but as command line argument. – user1934428 Apr 10 '18 at 05:46

3 Answers3

2

use any of the below methods, but i recommend the first one, since no subshell is been created

for files in *;do
   if [[ -f "$files" ]];then
       echo "$files"
   fi
done


while read line;do
   if [[ -f "$line" ]];then
       echo "$line"
   fi
done < <(ls)
0.sh
  • 2,659
  • 16
  • 37
0

You can use find, for example:

$ cat do.sh
#!/usr/bin/env sh

printf "arg: %s\n" "$1"
$ touch {1..10}
$ find . -type f -exec ./do.sh {} \;
arg: ./6
arg: ./10
arg: ./5
arg: ./3
arg: ./9
arg: ./2
arg: ./8
arg: ./do.sh
arg: ./1
arg: ./4
arg: ./7
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
0

You can use xargs.

$ find . -maxdepth 1 -print0 | xargs -0 -l command

this will print all of the files in your current directory, separating the names by null chars, then xargs take them, one at a time (-l) and invokes command using each file as an argument.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134