user1765441
user1765441

Reputation: 1

Copy all arguments but the last and paste them in the last argument in Bash

How to copy all the arguments but the last and paste them in the last argument in Bash?

All the arguments are file locations and the last argument is the folder location.

say I have two directories /a and /b /a contains x.txt y.txt z.txt and x.gz y.tar.gz and z.html

I need to have a script copy_script.sh which could be invoked as shown

./copy_script.sh /a/*.txt /b

and all txt files should be copied to /b

Upvotes: 0

Views: 305

Answers (3)

chepner
chepner

Reputation: 531708

It's possible to divide the arguments the way you want, but--as pointed out by others--unnecessary in this case.

$ set -- a b c d e
$ echo "${@:0:$#}"
a b c d
$ echo "${@: -1}"    # Space is necessary
e

Upvotes: 2

Mark Setchell
Mark Setchell

Reputation: 207660

You may not need to if you are trying to do this since the "mv" and "cp" commands already understand that the last item is a destination:

mkdir joe      # create directory
touch a b      # create two files here
mv a b joe     # move both to new directory
ls joe         # check they are there
a   b          # yes

Upvotes: 0

ederwander
ederwander

Reputation: 3478

Well this is a basic operation in bash and you dont need write a script to do what do you want, the cp command solve your problem just do:

cp a/*.txt b/

this copy all extensions .txt from directory a to directory b

Upvotes: 0

Related Questions