Bash – Spaces for variables in bash script

bashquotingshell-scriptvariable substitution

I have a space in one of the directory names. I want to list a file under it from a bash script. Here is my script:

fpath="${HOME}/\"New Folder\"/foobar.txt"

echo "fpath=(${fpath})"
#fpath="${HOME}/${fname}"

ls "${fpath}"

The output for this script is:

fpath=(/Users/<username>/"New Folder"/foobar.txt)
ls: /Users/<username>/"New Folder"/foobar.txt: No such file or directory

But when is list the file on my shell it exists:

$ ls /Users/<username>/"New Folder"/foobar.txt
/Users/<username>/New Folder/foobar.txt

Is there a way I can get ls to display the path from my script?

Best Answer

Just remove the inner quoted double-quotes:

fpath="${HOME}/New Folder/foobar.txt"

Since the complete variable contents are contained in double-quotes, you don't need to do it a second time. The reason it works from the CLI is that Bash evaluates the quotes first. It fails in the variable because the backslash-escaped quotes are treated as a literal part of the directory path.

Related Question