I have a bash function (slightly simplified for explaining)
copy_to() {
cp $1 $2 $3
}
This works fine:
copy_to -f /demo/example1.xml new_demo/
But Let’s say I want to copy all the xml files, the following code will have issues:
copy_to -f /demo/*.xml new_demo/
Obviously I could just write cp -f /demo/*.xml new_demo/, but is there anyway to get the copy_to function to work for a list of files (which passes more than just 3 parameters) as well as a single file?
There are
$@and$*which contain a list of all parameters. You should use$@, because it works inside of double quotes. Else, file names containing spaces would break your code.If one of the parameters is special, you can use the
shiftcommand to remove it from the list of parameters, like so:shiftremoves the first parameter from the list, therefore you’ll have to save it in another location first. After callingshift, the contents of$1will be what was$2,$2will contain what was$3and so on.$@expands to all parameters (excluding those that were removed byshift).Note that you cannot shift parameters off the end of your parameter list, only from the beginning.