1

How can I store a spaced string in a variable and use it as a command parameter inside a shell script?

This is what I'm trying to do:

DESTINATION='/mnt/External Harddisk'
FILE_NAME=$DESTINATION/home.tar.gz
INCREMENTAL=$DESTINATION/home.snar

tar -zcvpf $FILE_NAME \
--directory=/home \
--listed-incremental=$INCREMENTAL \
--exclude=.gvfs \
--exclude=.cache* \
--exclude=*/[Cc]ache* \
--exclude=.thumbnails* \
--exclude=*/[Tt]rash* \
--exclude=*~ \
--exclude=.dropbox* \
--exclude=*.vdi \
--exclude=*VirtualBox*VMs* \
.

2 Answers 2

2

this answer might cover it Spaces in Linux environmental variables?

You put the environment variable in double quotes. example demonstrating that below

I am doing ls 'asdf asdf' which is ls on one file 'adsf asdf' with a space in the filename. I want to do it with a variable. You see with double quotes it gets the result. With no quotes it treats the space as special and looks for the file asdf twice. And with single quotes ls '$f' it looks for literal dollar f. But with double quotes ls "$f" it works, i.e. gives same result as ls 'asdf asdf'.

$ ls 'asdf asdf' <ENTER>
ls: cannot access asdf asdf: No such file or directory

$ export f='asdf asdf' <ENTER>

$ echo $f <ENTER>
asdf asdf

$ ls $f <ENTER>
ls: cannot access asdf: No such file or directory
ls: cannot access asdf: No such file or directory

$ echo $f <ENTER>
asdf asdf

$ ls '$f' <ENTER>
ls: cannot access $f: No such file or directory


$ ls "$f" <ENTER>
ls: cannot access asdf asdf: No such file or directory
-1

Prepend any Space character with Escape string, so the Space will be in the string as '\ ' (backslash + space). Hope this help.

4
  • 1
    what do you mean? like this? doesn't work pastebin.com/raw.php?i=bCa90GYe
    – barlop
    Mar 9, 2015 at 2:11
  • 1
    The shell parses quotes and escapes before substituting variables, so putting quotes and/or escapes in the values of variables doesn't do anything useful. You need to put double-quotes around the variable reference. Mar 9, 2015 at 4:29
  • Please read the question again carefully. Your answer does not answer the original question.
    – DavidPostill
    Mar 9, 2015 at 6:22
  • Give an example and test it. You might even try it and find it doesn't work.
    – barlop
    Mar 9, 2015 at 8:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .