I want to write a function in bash that forwards arguments to cp
command.
For example:
for the input
<function> "path/with whitespace/file1" "path/with whitespace/file2" "target path"
I want it to actually do:
cp "path/with whitespace/file1" "path/with whitespace/file2" "target path"
But instead, right now I'm achieving:
cp path/with whitespace/file1 path/with whitespace/file2 target path
The method I tried to use is to store all the arguments in an array, and then just run the cp command together with the array. Like this:
function func {
argumentsArray=( "$@" )
cp ${argumentsArray[@]}
}
unfortunately, It doesn't transfer the quotes like I already mentioned, and therefore the copy fails.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.
You have to add the variable “$0” in the script as shown. On running the same “./” shell script command, the name of your shell script, e.g. “./filename” will be stored in the “$0” variable as an argument.
Just like $@
, you need to quote the array expansion.
func () {
argumentsArray=( "$@" )
cp "${argumentsArray[@]}"
}
However, the array serves no purpose here; you can use $@
directly:
func () {
cp "$@"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With