o_O
o_O

Reputation: 5737

Adding alias to bashrc to run multiple commands and pass a variable?

Not good at creating aliases but I have several commands to run and I want to do them all at once.

$ activator
$ clean
$ compile
$ run 9002

I would like to combine all of these commands into a single command like:

$ activate 9002

Normally I think I would know how to do this but the issue here is that it will need to wait until the previous command finishes and the prompt returns. Also, if I do an $ activate 9000 then the last command would run $ run 9000

Is there a way to do this in my alias?

Upvotes: 3

Views: 7518

Answers (4)

sarlam
sarlam

Reputation: 353

You can use 2 bash syntax system :

  • ";" to separate commands
  • "$1" as your first argument.

It gives you the following alias :

alias activate="activator;clean;compile;run $1"

Hope that help.

edit :

My bad. You can use $1 with functions, not aliases.

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295363

For the general case, an alias is the wrong tool for this job.

It'll work in this specific case, because it's only the last command to which arguments are being passed and there's no conditional logic required, but a function is the safer approach.

For instance, a shell function with exactly equivalent use to the alias could be written like so:

activate() { activator; clean; compile; run "$@"; }

...but you could also add other steps to be performed after the command taking arguments, which an alias doesn't allow:

activate() { activator; clean; compile; run "$@"; cleanup; }

Upvotes: 0

Ondrej
Ondrej

Reputation: 101

And if you want to continue the latter commands only when the former has finished successfully use && instead of ; like this:

alias activate="activator && clean && compile && run"

Upvotes: 3

Mr. Llama
Mr. Llama

Reputation: 20889

You can combine multiple commands in an alias using a semicolon:

alias name_goes_here='activator; clean; compile; run'

Then you can use name_goes_here 9002.

Alternately, if you need something more complex, consider making a function instead. They're considerably more flexible.

Upvotes: 3

Related Questions