使用密码的 Bash 脚本笨拙
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18971255/
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
Bash script awkwardness with pwd
提问by Vasiliy Stavenko
I've got a strange issue while working with a bash script. Here it is:
我在使用 bash 脚本时遇到了一个奇怪的问题。这里是:
PWD=${pwd}
# several commands
cd /etc/nginx/sites-enabled/
# more commands
cd $PWD
# I expect that I returning to my directory,
# but $PWD contains current dir - /etc/nginx/sites-enabled/
This behavior is kind of lazy. $PWD
stores command, which calculates the current directory and returns it at the moment we call $PWD
, but I want to store the string variable in it. How to do that?
这种行为有点懒惰。$PWD
存储命令,它计算当前目录并在我们调用的那一刻返回它$PWD
,但我想将字符串变量存储在其中。怎么做?
回答by Toam
PWD is an environmental variable and is changed when you change the directory.
PWD 是一个环境变量,当您更改目录时会更改。
Use a different name for the variable,
为变量使用不同的名称,
eg:
例如:
MYPWD=${PWD} #or MYPWD=$(pwd)
cd /etc/nginx/sites-enabled/
cd $MYPWD
回答by EJK
Try:
尝试:
PWD=`pwd`
Or:
或者:
PWD=$(pwd)
Both expressions will execute the pwdcommand and store the command output in the shell variable PWD. There is plenty of discussion on the web about when to use each style. The one point that I recall is that the "$(cmd)" approach allows for nesting of commands, e.g.
这两个表达式都将执行pwd命令并将命令输出存储在 shell 变量 PWD 中。网络上有很多关于何时使用每种样式的讨论。我记得的一点是“$(cmd)”方法允许嵌套命令,例如
CURRENT_BASENAME=$(basename $(pwd))
Edit - It just occurred to me that PWD is a built in shell variable that always expands to the current working directory.
编辑 - 我刚刚想到 PWD 是一个内置的 shell 变量,它总是扩展到当前工作目录。
回答by Brian Kuhns
you may also find
cd -
usefull
你也可能觉得
cd -
有用