5

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?

7

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.

5

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

Yes, use:

ls $HOME/New\ Folder/foobar.txt

The problem was that you were including the quotes inside the value of the variable. The real name of the directory does not have " quotes.

You need to build the variable with only one quoting method.

In variables:

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

Or:

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

Or even:

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

Full script:

#!/bin/bash
fpath=${HOME}/New\ Folder/foobar.txt
echo "fpath=(${fpath})"
ls "${fpath}"
3

The quotes are not part of the folder name, are they?

This should work:

fpath="$HOME/New Folder/foobar.txt"
ls "$fpath"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.