I know this question has been asked numerous times, but I still could not find any good solution. Hence, asking it again if anyone can help !!
I am trying to change a my working directory inside a shell script with help of a variable. But I get " No such file or directory"
everytime.
#!/bin/bash
echo ${RED_INSTANCE_NAME} <-- This correctly displays the directory name
cd $RED_INSTANCE_NAME <-- This line gives the error
Now, when I try to give the actually directory name instead of using the variable, shell changes the directory without issues
cd test <-- No error
Does anyone knows what can be the issue here ? Please help !!
You can check for carriage returns, ANSI escapes and other special characters with
This will show all the characters that
echo $RED_INSTANCE_NAME
would just hide or ignore.In particular, if your error message is
: No such file or directory
as opposed tobash: cd: yourdir: No such file or directory
, it means you have a carriage return at the end of your variable, probably from reading it from a DOS formatted file.I ran into a different issue. My "cd $newDir" was failing because I added logging into my script. Apparently if you add a pipe to any cd command it does nothing or gets gobbled up.
Wasted 3 hours figuring that out.
So cd with any pipe does nothing. No idea why cd fails. The pipe means finish what command you doing then feed any output to next command. This is on RHEL 7.
I was trying to log all my commands and hit this nice error. Figured I'd post it in case anyone else hits it.
I don't know what is going wrong for you, but I can offer one piece of general advice:
You should nearly always put the "$VARIABLE" in quotes. This will protect from surprises when the value of the variable contains funny stuff (like spaces).
One way to encounter your described problem is to have a tilde (
~
) in the variable name. Use the absolute path or$HOME
variable instead. Note that using$HOME
will require double quotations.Try
Also, make sure the path makes sense to the current directory where
cd
command is executed.You variable contains a carriage return. Try saying:
and it should work. In order to remove the CR from the variable you can say:
The following would illustrate the issue: