I have access to a list of folders that have a format like lastname, firstname(id) When I try to enter the folder from the terminal, it looks like cd test/lastname,\ firstname\(id\) I am not sure why there are backslashes where there aren't any spaces. My script has access to the credentials and I generated the exact format with the backslashes, but I still cannot enter the folder from the bash script. The variable I use is like this: folder="lastname,\ firstname\(id\)"

When I do cd $HOME/test/$folder/ it says there is not such folder. I tried a couple of solutions suggested on different questions, but haven't worked. Putting it within double quotes on the folder variable, and also on the entire expression also didn't work. I guess I don't know what is going wrong and hence cannot get it to work. It'd be awesome if someone could help me out here!



The variable I use is like this: folder="lastname,\ firstname\(id\)"

Will not work. Because the variable then keeps the backslash:

[maulinglawns@ArchLinux ~]$ folder="lastname,\ firstname\(id\)"
[maulinglawns@ArchLinux ~]$ echo "$folder"
lastname,\ firstname\(id\)

Hence, you get this message:

cd "slask/$folder" 
bash: cd: slask/lastname,\ firstname\(id\): No such file or directory

The easiest way to solve this is to put your variable inside "". Like this:

[maulinglawns@ArchLinux slask]$ mkdir lastname,\ firstname\(id\)
[maulinglawns@ArchLinux slask]$ folder="lastname, firstname(id)"
[maulinglawns@ArchLinux slask]$ cd "$folder"
[maulinglawns@ArchLinux lastname, firstname(id)]$ 

This way, the shell will not split on the whitespace in the variable. Read more about variables and quoting here.

  • dang dude! Thanks for educating me on these intricacies. I removed the extra backslashes that I was inserting manually and followed the method you suggested. Works! – rookie Oct 12 '16 at 6:51
  • @rookie No problem. Believe me, we have all been there! You posted a really good question. – maulinglawns Oct 12 '16 at 6:54

Quote your expansions ($folder is an expansion, a "Parameter expansion"):

$ cd "$HOME/test/$folder/"

If you assign the value in single quotes:

$ folder='lastname, firstname(id)'

There is no need for back quotes, and the above cd will work correctly.

  • I had actually tried the approach with single quotes manually and it worked. But then the problem was that the credentials(firstname/lastname/id) were pulled from different sources and the eventual folder name I created was stored in a variable. Now if I used single quotes, it didnt substitute the variable but used it as is and that's where I got stuck. – rookie Oct 12 '16 at 6:59
  • @rookie The take away should be "quote your expansions". That is the real key. – sorontar Oct 12 '16 at 7:03

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.