Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent bash alias from evaluating statement at shell start

Tags:

alias

bash

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?

like image 688
14 revs, 12 users 16% Avatar asked Nov 06 '12 23:11

14 revs, 12 users 16%


People also ask

How do I ignore an alias in bash?

Use the command command to ignore shell functions and aliases to run the actual external command. If you only want to avoid alias expansion, but still allow function definitions to be considered, then prefix the command with \ to just prevent alias expansion.

Can a bash alias take argument?

Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.

Can aliases be used within bash shell scripts?

'set alias' for any command and the alias command will work fine on the interactive shell, whereas aliasing doesn't work inside the script. Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

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.

like image 144
jordanm Avatar answered Sep 19 '22 05:09

jordanm


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.

like image 20
Raphael Payen Avatar answered Sep 19 '22 05:09

Raphael Payen