Martin Konecny
Martin Konecny

Reputation: 59601

Prevent bash alias from evaluating statement at shell start

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?

Upvotes: 38

Views: 9342

Answers (3)

jordanm
jordanm

Reputation: 34934

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.

Upvotes: 44

Raphael Payen
Raphael Payen

Reputation: 49

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.

Upvotes: 4

Lipongo
Lipongo

Reputation: 1261

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

Upvotes: 0

Related Questions