Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define alias that references other aliases

I'd need to be able to define an alias in a Debian shell that includes other aliases, for a project I'm currently working on.

Let's look at a code example to make things more clear.

  1. alias foo=foo
  2. alias bar=bar

If I run type foo it returns foo is aliased to 'foo', and type bar returns bar is aliased to 'bar'. Up to here all fine. Now, where I'm having the problem.

  1. alias foobar=$foo$bar

Doesn't work. type foobar returns foobar is aliased to ''.

I've tried alias foobar=${foo}${bar} and it doesn't work either.

Once I get this working, in the final version I actually need some text in between the two aliases, imagine something like: alias fooandbar=${foo}and${bar}.

Can anyone help please?

like image 855
Pensierinmusica Avatar asked Sep 10 '15 11:09

Pensierinmusica


People also ask

How do you indicate an alias?

The alias syntax The syntax for creating an alias is easy. You type the word "alias", followed by the name you want to give the alias, stick in an = sign and then add the command you want it to run – generally enclosed in single or double quotes. Single word commands like "alias c=clear" don't require quotes.

What does an alias do?

An alias lets you create a shortcut name for a command, file name, or any shell text. By using aliases, you save a lot of time when doing tasks you do frequently. You can create a command alias.

What is alias expansion?

Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias.

Where would you define an alias so that it is available each time you log in?

To have your alias definitions available anytime, define them in your . bashrc file. It is a hidden file in your home directory, and is executed automatically each time you open a terminal.


2 Answers

To reuse alias in another alias use:

foobar='foo;bar'

However I would suggest you to consider using shell function to get better control over this.

like image 69
anubhava Avatar answered Oct 06 '22 05:10

anubhava


Following @anubhava's sage advice:

foo() { echo foo; }
bar() { echo bar; }
foobar() { echo "$(foo)$(bar)"; }
fooandbar() { echo "$(foo)and$(bar)"; }

Spaces and semicolons inside {} are required there.

like image 44
glenn jackman Avatar answered Oct 06 '22 05:10

glenn jackman