在Bash变量分配的右侧引用时,波浪号没有扩展 [英] Tilde not expanded when quoting on the right hand side of a Bash variable assignment

查看:91
本文介绍了在Bash变量分配的右侧引用时,波浪号没有扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个目录〜/ test_myDir

I have made a directory ~/test_myDir

然后运行以下bash脚本:

I then run the following bash script:

x="myDir"

dirName="~/test_$x"

cd $dirName
echo "hey" > test.txt

我收到以下错误:

test.sh: line 5: cd: ~/test_myDir: No such file or directory

然后从第二个作业中删除引号:

I then remove the quotes from the second assignment:

x="myDir"

dirName=~/test_$x

cd $dirName
echo "hey" > test.txt

脚本运行无错误。

这是怎么回事?我在一个更大,更复杂的脚本中遇到了这个问题,然后将其范围缩小到我在包含另一个变量的变量赋值中使用引号。

What is going on here? I ran into this issue in a larger, more complicated script, and I narrowed it down to my use of quotes in a variable assignment that contained another variable.

错误消息,似乎完整路径已在 cd调用中正确扩展。

Still, from the error message, it looks like the full path is being expanded correctly in the "cd" call.

推荐答案

引号阻止扩展。将替换为 $ HOME 或使用 dirName =〜/ test_ $ x

Quotation marks prevent expansion of ~. Replace ~ with $HOME or use dirName=~/"test_$x".

根据手册中对代字扩展的解释:

From the manual's explanation of tilde expansion:


检查每个变量赋值是否紧跟在:或第一个=之后的不带引号的前缀。在这些情况下,也会执行波浪线扩展

Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tilde expansion is also performed.

这篇关于在Bash变量分配的右侧引用时,波浪号没有扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆