2

(Note: after some more research I have a partial answer, but I don't like having to write the actual commands against that variable differently depending on embedded spaces or not. I'll accept better suggestions).

I like to store various work variables in bash as I am working on something. This avoids having to type it up every time and also helps when you come back to work on it some time later (stick the assignment in a localprofile.sh file and source that later...).

I'd like to store a directory name with spaces in it. I know how to do deal with spaces in file/directory names interactively, using either quoting or \-based escaping:

$ ls -1 /Users/myuser/Library/Application\ Support/ | tail -5
iTerm2
icdd
org.videolan.vlc
pip
videosubscriptionsd

or

$ ls -1 "/Users/myuser/Library/Application Support/" | tail -5
iTerm2
icdd
org.videolan.vlc
pip
videosubscriptionsd

Now I'd like to assign that directory to a bash $dn variable and that's not working so well.

Here are some various tries. On purpose I stayed away from ~-based shell extension.

dn='/Users/myuser/Library/Application Support/'
echo ''
echo ''
echo $dn
ls -1 $dn

dn='"/Users/myuser/Library/Application Support/"'
echo ''
echo ''
echo $dn
ls -1 $dn

dn=/Users/myuser/Library/Application\ Support/
echo ''
echo ''
echo $dn
ls -1 $dn

dn="/Users/myuser/Library/Application\ Support/"
echo ''
echo ''
echo $dn
ls -1 $dn

each one of these shows a variation on ls: /Users/myuser/Library/Application\: No such file or directory

1 Answer 1

1

OK, found this by broadening by googling without specifying mac or osx - this is a generic bash issue: Stackoverflow how to add path with space in bash variable

And, translating that to my question, both "interactive approaches", i.e. quoting or \-escaping work, as long as you wrap the bash variable in its own double-quotes when you run the commands:

dn='/Users/myuser/Library/Application Support/'
ls -1 "$dn" | tail -5

dn=/Users/myuser/Library/Application\ Support/
ls -1 "$dn" | tail -5

Don't use single quotes above - there is no bash substitution happening in that case and you get ls: $dn: No such file or directory.

The drawback here is having to wrap the variables in double-quotes or not depending on embedded spaces.

dn="'/Users/myuser/Library/Application Support/'" and then not having quotes doesn't work, btw.

2
  • As a general rule: Always wrap variable names in "" when using them if you are not absolutely sure that their value does not contain spaces.
    – nohillside
    Commented Oct 14, 2017 at 12:23
  • It doesn't matter how you assign the value in the first place, all of foo='foo bar', foo="foo bar", foo=foo\ bar assign the same value.
    – nohillside
    Commented Oct 14, 2017 at 12:24

You must log in to answer this question.

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