[英]shell scripting variable substitution
I am puzzled about the variable substitution in shell scripting. 我对shell脚本中的变量替换感到困惑。 Here is the deal: I have following script. 这是交易:我有以下脚本。
if [ -d ~someone/Desktop ]
then
echo exist
fi
which would determine whether user "someone" has "Desktop" directory under his home directory. 这将确定用户“某人”是否在其主目录下具有“桌面”目录。 However, if I substitute the someone by other variable, it will not be correct. 但是,如果我用其他变量代替某人,那将是不正确的。 See below, 见下文,
var=someone
if [ -d ~${var}/Desktop ]
then
echo exist
fi
Although the user "someone" has Desktop directory, it will not print exist in the output. 尽管用户“某人”具有桌面目录,但在输出中将不打印该目录。 Can someone tell me why this happened? 有人可以告诉我为什么会这样吗?
var=someone
if [ -d $(eval echo ~${var})/Desktop ]
then
echo exist
fi
~user
is a special expression that is interpreted by the shell (for explanation, see man bash
-> Tilde Expansion). ~user
是由shell解释的特殊表达式(有关解释,请参见man bash
> Tilde Expansion)。 In your case the tilde isn't followed by a user name, so normal variable expansion takes place, ~$var
expands to a literal ~someone
, not to the usual /home/of/someone
. 在您的情况下,波浪号后面没有用户名,因此会进行普通的变量扩展, ~$var
扩展为文字~someone
,而不是通常的/home/of/someone
。
The quickest way of getting the user's home directory would be to grep it from /etc/passwd
: 获取用户主目录的最快方法是从/etc/passwd
grep它:
grep "^$var:" /etc/passwd | cut -d: -f6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.