2

I added an alias:

$ alias anyalias="echo kallel"

If I execute:

$ anyalias
kallel

it executes the echo command without any problem.

Now, if I define a variable in this way:

$ var="anyalias"

and then execute with this way:

$  $var
-ash: anyalias: not found

Then I got a shell error.

How I can make $var running the command defined in the anyalias alias?

I m not looking to change the way of calling $var. But I m looking for a way of changing the definition of the alias or export it.

3
  • "I look to change the alias definition and not the call of $var". You can't, alias doesn't work that way.
    – msw
    Nov 28, 2014 at 15:38
  • @msw In fact my real question is: I want to post execute a script when I call the ls command. So I add an alias ls: alias ls="/root/myscript.sh; ls". this alias will be exexute successfully whne I called it directly. but if I called wil a variable then it will not be executed as I expected
    – MOHAMED
    Nov 28, 2014 at 15:57
  • 1
    This question has been superceded by this one: stackoverflow.com/q/27193033/7552 Nov 28, 2014 at 18:22

2 Answers 2

6

Instead of alias consider using function:

anyfunc() { echo "kallel"; }
v=anyfunc
$v
kallel

Safer is to store the call of function in an array (will store arguments also, if needed):

var=(anyfunc)
"${var[@]}"
kallel
2
  • I look tochange the alias definition and not the call of $var.
    – MOHAMED
    Nov 28, 2014 at 14:59
  • In that case simply give your function same name i.e. anyalias() { echo "kallel"; } Then same var definition will work.
    – anubhava
    Nov 28, 2014 at 15:38
2

That's because alias expansion is performed previous to parameter expansion:
Command-line Processing

enter image description here

As you can see, you can go through the process again with eval, which is not recommended.
Instead, you can use some alternatives as the one by @anubhava.


Example

$ alias anyalias="echo kallel"
$ var=anyalias
$ $var
bash: anyalias: command not found
$ eval $var
kallel

Again, use eval carefully. It's just to illustrate the expansion process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.