0

I have a script yummy.sh

#!/bin/bash
alias yumy='yum install -y '
yumprovision() {
  yumy
}

When I run this script got this

bash: yumy: command not found

why it's not loading alias in function?

Akhil
  • 1,290

4 Answers4

3

You could use a function for yumy too:

#!/bin/bash
yumy() {
    yum install -y "$@"
}
yumprovision() {
    yumy
}

The "$@" expands to the arguments of that function, so yumy foo bar works the same as yum install -y foo bar.

Bash doesn't expand aliases in noninteractive shells by default, but you can change that with shopt expand_aliases if you really want, see The Shopt Builtin in the manual. But there's little reason to do that, functions are better in many ways.

ilkkachu
  • 138,973
2

Because aliases cannot be used in scripts. Aliases are only "converted" when entered at the terminal (otherwise writing scripts would be difficult, because you wouldn't now how ls or rm would react, for instance).

xenoid
  • 8,888
1

I believe variables are the alias of scripting.

You always can do the following, [But not recommended]

[arif@arif ~]$ yumi='yum install -y'

[arif@arif ~]$ $yumi tmux

Error: This command has to be run under the root user.

Why this method is not recommended and which way to follow is discussed at this link.

arif
  • 1,459
1

Apart from the visibility issues of aliases usually only being defined in interactive shells, you apparently need to use eval to execute the alias if the alias name is in a shell variable.

Demonstration

Here's a simple alias:

$ alias testing='echo this is test'

Simply referencing $this, even without quoting, does not work:

$ foo() { local this=testing; $this "$@"; }
$ foo bar
testing: command not found

One has to use eval to make this work:

$ foo() { local this=testing; eval $this '"$@"'; }
$ foo bar
this is test bar
Ingo Karkat
  • 11,864
  • 1
    yes, because aliases are expanded early, before actual syntactic parsing. Which is mostly another reason not to use them, unless you want to do the sort of tricks where messing with the syntax is an advantage. – ilkkachu Mar 24 '23 at 17:43