Shell脚本更改带有变量的目录 [英] 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 !!
我正在尝试借助变量在shell脚本中更改我的工作目录.但是我每次都会得到" No such file or directory"
.
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
现在,当我尝试提供实际的目录名称而不是使用变量时,shell会更改目录而不会出现问题
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 variable contains a carriage return. Try saying:
cd $(echo $RED_INSTANCE_NAME | tr -d '\r')
,它应该可以工作.为了从变量中删除CR,您可以说:
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
这篇关于Shell脚本更改带有变量的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!