Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy files with names containing spaces and UNICODE, when using a shell script?

I have a list of files that I'm trying to copy and move (using cp and mv) in a bash shell script. The problem that I'm running into, is that I can't get either command to recognize a huge number of files, seemingly because the filenames contain spaces and/or unicode characters. I couldn't find any switches to decode/re-encode these characters. Instead, for example, if I copy "file name.xml", I get "*.xml" and a script error that the file wasn't found for my result. Does anyone know settings or commands that will deal with these files?

EDIT(adding current code): When I run:

MacBookPro:Desktop$ ./script.sh

#!/bin/sh
dateVar=`date +%Y-%m-%d`
mkdir /Volumes/Documents/SMSarchive/$dateVar
cd /Volumes/Documents/SMSarchive/SMSdrop
for i in *.xml
do
cp $i /Volumes/Documents/SMSarchive/$dateVar/$dateVar-$i
done

I get the message:

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-pvX] source_file target_file cp [-R [-H | -L | -P]] [-fi | -n] [-pvX] source_file ... target_directory

...when it hits the "cp" command. There's actually more to the script, that processes the copied files further. With a "regular" file name e.g. 'file.xml', everything works fine. It's only files with spaces, or Unicode characters, where I have problems.

like image 451
LOlliffe Avatar asked Mar 31 '10 05:03

LOlliffe


1 Answers

Problems with spaces indicates that insufficient quoting has been done. The following is incorrect:

someprogram $file

The correct version is as follows:

someprogram "$file"
like image 102
Ignacio Vazquez-Abrams Avatar answered Oct 26 '22 23:10

Ignacio Vazquez-Abrams