必须确定所有用户的主目录 - 波形符脚本问题
假设 someuser 有一个主目录 /home/someuser
NAME=someuser
在 bash 中 - 我使用什么表达式组合波浪号 (~) 和 $NAME 来返回用户主目录?
HOMEDIRECTORY=~someuser
echo $HOMEDIRECTORY
/home/someuser
NAME=someuser
echo ~$NAME
~someuser
有什么建议吗?
Assume someuser has a home directory /home/someuser
NAME=someuser
In bash - what expression to I use combining tilde (~) and $NAME to return the users home directory?
HOMEDIRECTORY=~someuser
echo $HOMEDIRECTORY
/home/someuser
NAME=someuser
echo ~$NAME
~someuser
any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更安全:
此处
printf
的%q
选项引用并转义危险字符。如果
$NAME
是 joe,您会得到类似/home/joe
的内容。对于 root,您可能会得到/root
。对于“abc;rm some”,您会得到“~abc;rm some”,而不是删除某些内容。Safer:
Here the
%q
option toprintf
quotes and escapes dangerous characters.If
$NAME
is joe, you'd get something like/home/joe
. For root, you might get/root
. For "abc;rm something" you'd get "~abc;rm something" instead of having something removed.如果您有权访问
getent
:If you have access to
getent
:bash 和 csh 之间有趣的区别,其中 ~$VARNAME 实际上执行了您所期望的操作!
这很难看,但它似乎可以在 bash 中工作:
现在 $homedir 保存与 $USERNAME 关联的主目录。
Interesting difference between bash and csh, where ~$VARNAME actually does what you'd expect!
This is ugly, but it seems to work in bash:
Now $homedir holds the home directory associated with $USERNAME.
最佳方法
必需:无
(注意,这与 getent 技术相同,不需要 getent)
ROOT LINUX 的好方法
必需:Linux ,root(或sudo)
完整扩展的解决方案
示例用法:
利用 CSH 的方法
这是一个 BASH 脚本,它只是调用csh。
必需:csh
绝望方法
必需:finger(已弃用)
您可以将 grep 操作合并到 sed,但由于这种方法很糟糕,所以我不会打扰。
BEST METHOD
Required: nothing
(n.b., this is the same technique as getent without requiring getent)
NICE METHOD FOR ROOT LINUX
Required: Linux, root (or sudo)
SOLUTION FOR COMPLETE EXPANSION
Example usage:
METHOD FOR HARNESSING CSH
This is a BASH script, it just calls csh.
Required: csh
METHOD OF DESPERATION
Required: finger (deprecated)
You can combined the grep operation into sed, but since this method is sucky, I wouldn't bother.
一种替代方法
one alternative way
波形符 ( ~ ) 与 $HOME 相同,因此并非所有用户都以 root 身份访问同一目录。
但是,如果您坚持使用波浪号,则可以完成此工作:
请参阅:
Tilde ( ~ ) it's the same as $HOME so, not all the user will have as root to home the same directory.
But if you insist in using the tilde this do the work:
See: