Linux 获取变量中的当前路径并使用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1636363/
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-08-03 17:50:13  来源:igfitidea点击:

Getting current path in variable and using it

linuxbash

提问by R0b0tn1k

I would like to extract the current path in a variable and use it later on in the script

我想提取变量中的当前路径并稍后在脚本中使用它

Something like:

就像是:

myvar = pwd

Later on:

稍后的:

cd myvar

But my bash skills have rusted over the years.

但是这些年来我的 bash 技能已经生锈了。

How would i go on about doing that?

我将如何继续这样做?

采纳答案by digitalarbeiter

myvar="$PWD"
cd "$myvar"

(Quotes are necessary if your path contains whitespaces.)

(如果您的路径包含空格,则需要引号。)

回答by Luká? Lalinsky

Something like this should work:

这样的事情应该工作:

myvar=`pwd`
# ...
cd $myvar

回答by ghostdog74

in bash

在 bash

$ a=$(pwd)

回答by Joachim Sauer

Ind addition to the pwdcommand and the $PWDenvironment variable, I'd also suggest you look into pushd/popd:

除了pwd命令和$PWD环境变量之外,我还建议您查看pushd/ popd

/$ pushd /usr
/usr /
/usr$ pushd /var/log
/var/log /usr /
/var/log$ popd
/usr /
/usr$ popd
/
/$

回答by EliuX

It worked for me:

它对我有用:

currentdir=$(cd -)
printf "Generating content at $currentdir\n"