简体   繁体   中英

Bash: Copy all arguments that are files to a directory

I have an executable called a.sh. It takes in an unknown number of arguments. From the list of arguments, I want to copy all the ones that are files into another folder, (/myfolder).

For example, if I type this on the command line:

./a.sh foo.out | tee -a text.txt

Assuming foo.out and text.txt both exist, I want to copy them to myfolder.

I'm currently thinking about writing all the arguments to a file and reading the file line by line, checking with an if [ -f ] statement. Is there a neater/cleaner solution out there?

Thanks!

Slightly tricky because the files you list aren't actually all arguments to a.sh. The shell splits them up so foo.out is an argument of a.sh and text.txt is an argument of tee. The only way to do what you suggest would be to store this whole command line in a string, process the files out of it and then eval the string.

(Here I assume the pipe symbol was in the question by mistake.)

There is no need to write to a file, since you can easily check the arguments, without knowing how many there are.

for arg ; do
  if [ -f $arg ]; then
    cp $arg myfolder
  fi
done

For will loop through the arguments by default, which is used here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM