This is what I tried.

inputFile=$(zenity --file-selection --title "Test" --text "Please select the file for analysis." | sed -e "s/ /\\\ /g")

I did the sed operation to replace white spaces with a \ and a whitespace to make the copying command to work. Then from the Zenity file selection GUI I have chosen a file so that the value inside inputFile is /home/username/Documents/Learning\ and\ Development/testfile.txt.

Now when I try to copy this file to my working directory with

cp $inputFile .

Still it returns the error,

cp: cannot stat ‘/home/user/Documents/Learning\\’: No such file or directory
cp: cannot stat ‘and\\’: No such file or directory
cp: cannot stat ‘Development/WhatsApp.apk’: No such file or directory

Is there any way to bypass this? Actually I am writing a program. So I don't want to tell the users to rename their folder names to avoid spaces.

  • 4
    How about cp "$inputFile" .? – Jos Jul 15 '15 at 7:09

Easily you can do the trick, enclose by double quotes:

cp "$inputFile" /destination/

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, Read more: http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html

  • Omg! It worked. I burned hell lot of time on this. My bad :( By the way, I had to remove the sed operation I did in order to work this :) – Anonymous Platypus Jul 15 '15 at 7:15
  • Works like a charm just add a " to encapsulate the path. thanks for sharing – Doogle May 14 '19 at 3:23

you can add * where the space appeared and the copy can be done like

 cp  /home/user/users*tst.txt  /home/user/Downloads

where you want to copy users tst.txt to Downloads folder from home folder

  • instead of * you can use ? too – Dark Prince Aug 1 '17 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.