Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash - surround all array elements or arguments with quotes

Tags:

linux

bash

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.

like image 843
Alex Weitz Avatar asked Mar 08 '16 13:03

Alex Weitz


People also ask

What is $@ in bash?

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.

How do you escape quotes in bash?

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.

How do I pass an argument in bash?

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.


1 Answers

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 "$@"
}
like image 67
chepner Avatar answered Oct 05 '22 11:10

chepner