LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   moving files that have spaces in variables -bash scripting (https://www.linuxquestions.org/questions/programming-9/moving-files-that-have-spaces-in-variables-bash-scripting-365731/)

bhar0761 09-21-2005 05:49 PM

moving files that have spaces in variables -bash scripting
 
I seem to not be able to move or copy files that have spaces that are contained in variables.
for instance
v1=$(ls *.html)
mv $v1 /opt

if files have spaces then i get an error trying to move them because it tries to break up file names.

I have tried
ls -Q
for loops
ls --quoting-style=shell
mv "$v1" /opt
?

Tinkster 09-21-2005 07:46 PM

mv "$v1" /opt
should work ...


Cheers,
Tink

bhar0761 09-21-2005 08:35 PM

no that does not work either, i forgot to list it in the tried section.

Tinkster 09-21-2005 08:53 PM

What about a completely different approach?

find -maxdepth 1 -iname "*html" -exec mv "{}" /opt/. \;


Cheers,
Tink

bhar0761 09-21-2005 09:16 PM

Yes that did work, but I need to work with the files stored in a variable before the move.

It is weird to me that the command doesn't work or are we just missing something?

Tinkster 09-21-2005 09:22 PM

Quote:

Originally posted by bhar0761
no that does not work either, i forgot to list it in the tried section.
Hmmm .. what DOES it do when invoked like that?


Cheers,
Tink

bhar0761 09-21-2005 09:25 PM

mv "$var1" /opt
mv: cannot stat `index 1.out\nindex 2.out': No such file or directory

Dark_Helmet 09-21-2005 10:16 PM

This is the way I've always done it, but it doesn't seem to be extremely popular:
Code:

#!/bin/bash

# Do initial script stuff

old_ifs=${IFS}
IFS=$'
'

for file in $( ls *.html )
do
  mv "${file}" /opt
done

IFS=${old_ifs}

# Do more stuff


bhar0761 09-22-2005 12:28 AM

thank you, that does work
can you explaing IFS ' ' thing? or point me in the right direction


thanks again

Dark_Helmet 09-22-2005 12:43 AM

IFS is an environment variable used by the shell to determine where to break a list of items into single items. In other words, the IFS variable contains a list of delimeters that mark the end of an item. (man bash and search for IFS if you want to know the gory details) By default, IFS is defined to include space, tab, and newline. Normally this is what people want. So, the magic hand-waving at the top of the script saves the existing value of IFS in a temporary variable, sets IFS to include only the newline character, and that forces bash to treat files with spaces as a single item. Then, it restores the IFS to the original value in case the script has anything else to do that relies on the original value of IFS.

bigearsbilly 09-22-2005 07:30 AM

ls | cpio -pd /opt


All times are GMT -5. The time now is 09:00 AM.