Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script change directory with variable

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 !!

like image 574
Vivek Avatar asked Oct 09 '13 19:10

Vivek


2 Answers

You variable contains a carriage return. Try saying:

cd $(echo $RED_INSTANCE_NAME | tr -d '\r')

and it should work. In order to remove the CR from the variable you can say:

RED_INSTANCE_NAME=$(echo $RED_INSTANCE_NAME | tr -d '\r')

The following would illustrate the issue:

$ mkdir abc
$ foo=abc$'\r'
$ echo "${foo}"
abc
$ cd "${foo}"
: No such file or directory
$ echo $foo | od -x
0000000 6261 0d63 000a
0000005
$ echo $foo | tr -d '\r' | od -x
0000000 6261 0a63
0000004
$ echo $'\r' | od -x
0000000 0a0d
0000002
like image 125
devnull Avatar answered Oct 30 '22 06:10

devnull


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.

# doesn't work
$ vartilde='~/'
$ cd $vartilde
-bash: cd: ~: No such file or directory

# works
$ varfullpath='/Users/recurvirostridae'
$ cd $varfullpath

# works
$ varwithhome="$HOME"
$ cd $varwithhome
like image 25
trailing slash Avatar answered Oct 30 '22 07:10

trailing slash