bash:~扩展内部shell脚本

bash:~扩展内部shell脚本,bash,shell,Bash,Shell,我试图编写一个简单的shell脚本来构建一个用于分析的管道,其中一个步骤是构建一个指向现有目录和文件的符号链接 最初我是这样设置的: dir='~/project/xxxx/' ln -s $dir . 但是,上面的代码不起作用 我发现~在执行时没有在shell脚本中展开 我尝试在目录路径中使用双引号而不是单引号,但这也不起作用 以下措施奏效了 dir="$HOME/project/xxxx/" ln -s $dir . 我只是想知道为什么~不起作用。这种现象的正式名称是什么 谢谢 在任何类

我试图编写一个简单的shell脚本来构建一个用于分析的管道,其中一个步骤是构建一个指向现有目录和文件的符号链接

最初我是这样设置的:

dir='~/project/xxxx/'
ln -s $dir .
但是,上面的代码不起作用

我发现~在执行时没有在shell脚本中展开

我尝试在目录路径中使用双引号而不是单引号,但这也不起作用

以下措施奏效了

dir="$HOME/project/xxxx/"
ln -s $dir .
我只是想知道为什么~不起作用。这种现象的正式名称是什么


谢谢

在任何类型的引号内都不会发生波浪式展开。因此,例如,使用:

dir=~'/project/xxxx/'
还请注意,如果使用~username/格式,则用户名/部分也必须是无引号的。来自man bash:

瓷砖膨胀

   If a word begins with an unquoted tilde character (`~'),  all  of
   the characters preceding the first unquoted slash (or all charac‐
   ters, if there is no unquoted slash) are considered a  tilde-pre‐
   fix.   If  none of the characters in the tilde-prefix are quoted,
   the characters  in  the  tilde-prefix  following  the  tilde  are
   treated as a possible login name.  If this login name is the null
   string, the tilde is replaced with the value of the shell parame‐
   ter  HOME.  If HOME is unset, the home directory of the user exe‐
   cuting the shell is substituted instead.  Otherwise,  the  tilde-
   prefix  is  replaced  with the home directory associated with the
   specified login name.

平铺扩展不会在任何类型的引号内发生。因此,例如,使用:

dir=~'/project/xxxx/'
还请注意,如果使用~username/格式,则用户名/部分也必须是无引号的。来自man bash:

瓷砖膨胀

   If a word begins with an unquoted tilde character (`~'),  all  of
   the characters preceding the first unquoted slash (or all charac‐
   ters, if there is no unquoted slash) are considered a  tilde-pre‐
   fix.   If  none of the characters in the tilde-prefix are quoted,
   the characters  in  the  tilde-prefix  following  the  tilde  are
   treated as a possible login name.  If this login name is the null
   string, the tilde is replaced with the value of the shell parame‐
   ter  HOME.  If HOME is unset, the home directory of the user exe‐
   cuting the shell is substituted instead.  Otherwise,  the  tilde-
   prefix  is  replaced  with the home directory associated with the
   specified login name.

只需从引号中取出平铺:dir=~/'project/xxxx/'

只需从引号中取出平铺:dir=~/'project/xxxx/'

不正确,它不会在单引号中展开

那是谎言,它也不会扩大

使用~不带引号,或使用$HOME不带引号/双引号

请记住,可以使用各种引号连接字符串:

echo a"b"'c'
abc
如果有助于可读性,请从路径中移出

我的建议是:选择$HOME

不正确,它不会在单引号中展开

那是谎言,它也不会扩大

使用~不带引号,或使用$HOME不带引号/双引号

请记住,可以使用各种引号连接字符串:

echo a"b"'c'
abc
如果有助于可读性,请从路径中移出

我的建议:更喜欢$HOME。

+1使用$HOME代替。~与其说是主目录的可靠构造函数,不如说是减少键入的别名。+1用于使用$home。~与其说是主目录的可靠构造函数,不如说是减少键入的别名。