Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include an environment variable inside an alias for bash?

Tags:

bash

I am pretty new to bash, and I want to include an env for bash aliases.. I want to do something like the following

alias foo="bar $(baz)" 

So that I could do something like the following

> baz=40 > foo 

and foo will expand to the command bar 40. Currently the above does not work because $(baz) is expanded while making the alias. Do I have to wrap this inside a function or something?

like image 832
Doboy Avatar asked Jun 23 '12 19:06

Doboy


People also ask

How do I pass an environment variable in bash script?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

Are aliases environment variables?

So now we might find a little clearer where the differences are between aliases and environment variables, yes, they are both like keywords, but an alias holds a reference to a command and an environment variable just withholds data.


Video Answer


2 Answers

You need to use single quotes (') to prevent bash from expanding the variable when creating the alias:

$ alias foo='echo "$bar"' $ bar="hello" $ foo hello 
like image 188
Kenneth Hoste Avatar answered Oct 04 '22 04:10

Kenneth Hoste


Aliases don't have an "environment". An alias is simply a "dumb" text substitution. In the question, an environment variable isn't being used - only a shell variable. If you want to use the environment, use a function. In this case, there is no advantage to an alias over a function.

$ alias foo='echo "$bar"' $ bar=hi foo 

This produces no output because the environment set for a simple command doesn't apply to expansions.

$ alias foo=$'eval \'echo "$bar"\'' $ bar=hi foo hi 

If a function were used instead, there wouldn't be a problem.

$ foo() { echo "$bar"; } $ bar=hi foo hi 

When in doubt, always use a function.

Edit

Technically, the above is bash-only. Doing this in a fully portable way is nearly impossible.

In dash, mksh, bash POSIX mode, and other POSIX shells you can do:

foo() { echo "$bar"; } bar=hi command eval foo 

However, this won't work in ksh93 or zsh. (I've already reported a bug for ksh93 but it may never be fixed.) In mksh and ksh93 you should instead define functions using the function keyword, but that isn't POSIX. I'm not aware of any solution that will work everywhere.

To make matters worse, extra exceptions are being added to POSIX 2008-TC1 so that the way environment assignments work will be even more complicated. I suggest not using them unless you really know what you're doing.

like image 24
ormaaj Avatar answered Oct 04 '22 04:10

ormaaj