bash 在 shell 脚本中将脚本目录更改为用户的 homedir

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/521226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:40:20  来源:igfitidea点击:

Change script directory to user's homedir in a shell script

linuxbashshell

提问by Sergey Golovchenko

In my bash script I need to change current dir to user's home directory.

在我的 bash 脚本中,我需要将当前目录更改为用户的主目录。

if I want to change to user's foohome dir, from the command line I can do:

如果我想更改为用户的foo主目录,我可以从命令行执行以下操作:

cd ~foo

Which works fine, however when I do the same from the scriptit tells me:

哪个工作正常,但是当我从脚本中执行相同操作时,它告诉我:

./bar.sh: line 4: cd: ~foo: No such file or directory

Seams like it would be such a trivial thing, but it's not working. What's the problem here? Do I need to escape the "~" or perhaps missing quotes or something else?

接缝就像是一件微不足道的事情,但它不起作用。这里有什么问题?我是否需要转义“〜”或可能缺少引号或其他东西?

Edit

编辑

when I say userI don't mean currentuser that runs the script, but in general any otheruser on the system

当我说用户时,我不是指运行脚本的当前用户,而是指系统上的任何其他用户

Edit

编辑

Here is the script:

这是脚本:

#!/bin/bash

user="foo"
cd ~$user

if username is hardcoded like

如果用户名是硬编码的

cd ~foo

it works, but if it is in the uservariable then it doesn't. What am I missing here?

它有效,但如果它在用户变量中,则它不会。我在这里错过了什么?

回答by Johannes Weiss

What about

关于什么

cd $(getent passwd foo | cut -d: -f6)

and

USER=foo
eval cd ~$USER

works, too (foo is the username)

也有效(foo 是用户名)

回答by Sean Bright

Change it to:

将其更改为:

cd $HOME

Actually, I'm not sure why cd ~whateverwouldn't work. I've just tested with a small script and it worked fine:

实际上,我不确定为什么cd ~whatever不起作用。我刚刚用一个小脚本进行了测试,它运行良好:

#!/bin/bash

cd ~sbright

I actually get the same error message that you do when the specified user does not exist on the system. Are you sure (and yes, I know this is one of those is-it-plugged-in questions) that the user exists and has a valid home directory specified?

当指定的用户在系统上不存在时,我实际上收到了与您相同的错误消息。您确定(并且是的,我知道这是插入的问题之一)用户存在并指定了有效的主目录吗?

Edit:

编辑:

Now that I see what you are actually doing... tilde expansion happens before variable interpolation, which is why you are getting this error.

现在我看到了您实际在做什么...波浪号扩展发生在变量插值之前,这就是您收到此错误的原因。

回答by Mick T

Is the script going to be run by the user? If it is you can just do: cd ~

脚本是否将由用户运行?如果是,你可以这样做: cd ~

回答by JSB????

Is there some reason you can't do:

有什么原因你不能这样做:

#!/bin/bash

cd /home/$USER

Of course directories aren't in /home on all *nixes, but assuming you know what OS/distro your script is targeted for, you should be able to come up with something that works well enough.

当然,目录并不在所有 *nix 上的 /home 中,但假设您知道脚本的目标操作系统/发行版,您应该能够想出一些运行良好的东西。