File paths with spaces in a variable

Hi all my very first post so go easy on me!!

I am trying to build a very simple script to list a file path with spaces in. But I can't get around this problem. My script is as follows:

#!/bin/bash
X="/Library/Users/Application\ Support/"

LS="ls"
AL="-al"

$LS $AL $X

The response I get is this

ls: /Library/Application\: No such file or directory
ls: Support/: No such file or directory

I know this is a problem with the space in the file path but I thought the "" would pass to the commandline with no issues but I am wrong.

Try double quoting to preserve spaces:

$LS $AL "$X"

And the back-slash is unnecessary in the path:

X="/Library/Users/Application Support/"

That has worked :slight_smile: Thank you !!

So am I quoting in the wrong place? Should I quote when the variable is defined or when it is read

i.e. "$X" and $X

When defining, you can use quotes, but also escape spaces like "\ ". When referencing, double quotes keep the shell from splitting the variable's contents into several words at spaces.

No problem: would you please use CODE-tags when posting code? Thank you.

True. The problem is in the last line: your definition of "X" is ok, since the space is protected there (try removing the double quotes and you will get an error if you remove the escape "\" too). But when your script gets to the last line it first replaces "$X" with its contents and only then executes the line. This is "ls" is presented two parameters, separated by a space (which was no longer protected) the first and the second part of "$X". "ls" is fine with getting two paths, but these two paths, "/Library/Users/Application" and "Support/" do not exist, hence you get two errors, one for the first missing path and one for the second.

Use

$LS $AL "$X"

or, if you are completely paranoid, like me:

"$LS" "$AL" "$X"

and it will work as expected.

I hope this helps.

bakunin