Search code examples
bashshellescapingargs

How to cp / mv or command to a filename set in a variable containing particular character in shellscript?


I run my script via console:

sh ./application.sh CurriculumVitae\ \(January\ 2020\).pdf

containing backslashes to allow special characters escaping.

In the application.sh I need to make a copy of this input file so I run the following code to actually add those backslashes and copy it:

ORIGINAL_FILE="$1"
COMMAND_FILE=$( echo "$ORIGINAL_FILE" | sed 's/ /\\ /g' )

eval cp "$COMMAND_FILE" ".temp/"

where $1 is CurriculumVitae (January 2020).pdf and $ORIGINAL_FILE is CurriculumVitae\ \(January\ 2020\).pdf.

But my eval cp "$COMMAND_FILE" ".temp/" fails with the following error:

./application.sh: eval: line 52: syntax error near unexpected token `('
./application.sh: eval: line 52: `cp CurriculumVitae\ \(January\ 2020\).pdf .temp/'

How can I solve this within the variable? Thanks


Solution

  • The three lines commands should be replaced simply with this one cp "$1" ".temp/"