0

I came across a strange problem. If I enter in terminal cd "folder" (with quotes around folder name), it works.

But if I use the code bellow in my bash script, it gives me an error saying that the folder doesn't exist.

path="\"folder\""
echo $path   ---> outputs "folder", with quotes
cd $path

I am located in the same folder when I write cd "folder" in terminal and when I run the script bellow.

What is the problem?

EDIT: To make myself clear. I need to use quotes around folder name because some of the folders contain spaces.

Mike Davidson
  • 53
  • 1
  • 1
  • 5

3 Answers3

0

The shell will expand the parameters once. With cd "folder" the quotes are removed before the cd is executed. Fine.
With cd $path the shell will translate $path in a string with quotes. cd tries to find the directory with quotes in the name.

Walter A
  • 19,067
  • 2
  • 23
  • 43
0

You need to put quotes like below:-

 cd "$path"
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
0

You are trying to go to '"folder"' not to 'folder' than mean you are trying to access to "folder" not to folder. I guess you want to access folder.

Quote are to define a string, in your case, you do not need it in the string content. When you write cd "folder" you define a string witch contain folder

You must rework your data's source to remove unwanted quote.

Like @Abhijit Pritam answered, if you have space or character that could be interpreted by the shell, you can surround your variable by doubles quotes: cd "$path". As specified in the manual:

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.

[...]The characters ‘$’ and ‘`’ retain their special meaning within double quotes

So the code, with removed double quotes from the data's source:

path="folder with space"
echo -n $path   ---> outputs folder with space
cd "$path"

I suggest you to do not have space in folder's name, it prevents space issues.

Community
  • 1
  • 1
Ngob
  • 446
  • 4
  • 11