Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 6 down vote accepted

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.

share|improve this answer

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}"
share|improve this answer

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

This should work:

fpath="$HOME/New Folder/foobar.txt"
ls "$fpath"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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