Prevent bash alias from evaluating statement at sh

2020-05-29 21:07发布

问题:

Say I have the following alias.

alias pwd_alias='echo `pwd`'

This alias is not "dynamic". It evaluates pwd as soon as the shell starts. Is there anyway to delay the evaluation of the expression in the ticks until the alias's runtime?

回答1:

What you really want is a function, instead of an alias.

pwd_alias() {
   echo "$PWD"
}

Aliases do nothing more than replace text. Anything with complexity calls for a function.



回答2:

As jordanm said, aliases do nothing more than replace text.
If you want the argument of echo to be the output of pwd expanded by bash, then I don't understand your question.
If you want the argument of echo to be `pwd` with the backquotes kept, it's indeed possible, for example:

alias a="echo '\`pwd\`'"

So, if instead of echo you have something which does backquote expansion in its own runtime, maybe that's what you want.



回答3:

I do not believe you can change the evaluation from occurring at shell start. Since the processes of creating the alias is run at shell start the pwd is evaluated then. You could simple change the alias to just run pwd without the back ticks as pwd outputs without the need to echo. A simple way to resolve this is to change from using an alias to a shell script in your path if you do not wish to change from using an alias.

#!/bin/bash
pwd


标签: bash alias