Wednesday, July 27, 2022

[SOLVED] Bash alias name from a variable

Issue

Is there a way to make a bash alias (or function) with its name coming from a variable?

For instance, is it possible to do something along these lines:

create_alias_with_name() {
  alias $1="echo a custom alias"
}

Or something along these lines:

create_func_with_name() {
  $1() {
    "echo inside a function with a variable name"
  }
}

In other words, I would prefer to have some kind of function "factory" that can register functions for me. Is this possible or beyond the capabilities of Bash?


Solution

Did you even try it? Your first example works fine.

You can make the second work by adding an eval:

create_func_with_name() {
  eval "$1() {
    echo inside a function with a variable name
  }"
}


Answered By - Carl Norum
Answer Checked By - Willingham (WPSolving Volunteer)