如何在 bash 中为导出设置别名

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

How to alias an export in bash

bashexportalias

提问by Sreeram Ravinoothala

I am trying to set an env variable which I can use to do relative directory chanes. I am trying to do it the following way but cant get it to work. How do I do it?

我正在尝试设置一个 env 变量,我可以用它来做相对目录的更改。我正在尝试按以下方式执行此操作,但无法使其正常工作。我该怎么做?

alias sroot="export SROOT="$PWD""
alias drumit="cd $SROOT/abc/def/drumit"

If I type sroot, it takes the alias but when i type drumit, it gives me an error saying

如果我输入 sroot,它会使用别名,但是当我输入drumit 时,它会给我一个错误提示

bash: cd: /abc/def/drumit: No such file or directory

Looks like when the shell was launced it takes $SROOTas .Appreciate any help.

看起来像当外壳被launced它需要$SROOT.感谢所有帮助。

Thanks

谢谢

回答by Keith

Your $PWD and $SROOT variables are being expanded at the time you define the aliases, not when you are using them. Put a \ in front of them to escape them while they are defined.

您的 $PWD 和 $SROOT 变量在您定义别名时被扩展,而不是在您使用它们时。在定义它们时在它们前面放一个 \ 以逃避它们。

alias sroot="export SROOT="$PWD""
alias drumit="cd $SROOT/abc/def/drumit"

回答by chown

When you initially set the alias, it expands $PWDinstead of keeping it as the variable form. Try using functioninstead like this:

当您最初设置别名时,它会扩展$PWD而不是将其保留为变量形式。尝试function像这样使用:

$ function sroot {
> export SROOT="$PWD"
> }
$ export -f sroot
$ function drumit {
> cd $SROOT/cron
> }
$ export -f drumit
$ declare -f sroot
sroot()
{ 
    export SROOT="$PWD"
}
$ declare -f drumit
drumit ()
{
    cd $SROOT/abc/def/drumit
}


This is what is currently happening when you alias like in your question (variable expanding):

当您在问题中使用别名(变量扩展)时,这就是当前正在发生的事情:

$ alias sroot="export SROOT="$PWD""
$ alias drumit="cd $SROOT/abc/def/drumit"
$ alias
alias SROOT='/home/jon'
alias drumit='cd /home/jon/abc/def/drumit'
alias sroot='export SROOT=/home/jon'

Escaping would work too:

转义也可以:

$ alias sroot="export SROOT="$PWD""
$ alias drumit="cd $SROOT/abc/def/drumit"
$ alias
alias drumit='cd $SROOT/abc/def/drumit'
alias sroot='export SROOT=$PWD'