2

In my .bash_profile I have created alias to commands that I run often.

What if I want to group together multiple commands together, and they should run in serial one after the other.

How would I do this?

3 Answers 3

5

You can create a function instead of an alias:

function foo {
    cat somefile.txt
    rm anotherfile.txt
}

You can even pass parameters (foo somefile.txt) and use them as arguments to the commands (e.g. cat $1 for the first argument).

This approach is more flexible than creating an alias.

4
  • I like that, so is this bash script?
    – user27449
    May 18, 2011 at 19:34
  • @user No, a bash script is a file, typically with a .sh extension, that starts with #!/bin/bash or #!/usr/bin/env bash, and is invoked like any other program and contains shell commands and program invocations. The advantage to that is that it's available even in environments that don't load your .bash_profile, like other shells, can be copied like regular files, and work without editing the .bash_profile of every user who wants to use them.
    – Daniel Beck
    May 18, 2011 at 19:36
  • 1
    @user27449 Shell startup files such as .bash_profile ARE shell scripts. When you put stuff in those files, you are shell scripting even if you don't realize it. Anything you can do in a separate ".sh" shell script file you can do in your startup files, and you can do at the interactive shell prompt; shells use the same syntax everywhere. It's part of their beauty.
    – Spiff
    May 18, 2011 at 19:47
  • @Spiff Good comment. I have to add, functions like the one in my answer can be part of bash scripts, but aren't scripts themselves.
    – Daniel Beck
    May 18, 2011 at 19:50
5

Concatenate them with &&, for example

cat somefile.txt && rm anotherfile.txt

Note that chaining it this way the commands depend on the exit state of their preceding one, so if any command would fail, the execution of the whole line would stop at that point.

3
  • 1
    for this reason I think that the ';' is more appropriate, if you do not want your command to be dependant of each other
    – Yab
    May 19, 2011 at 6:03
  • @Yab Depends on the use case. For example, if you use git and there's something wrong when adding files to the local repository, why would you want to push "nothing" afterwards?
    – slhck
    May 19, 2011 at 7:34
  • That's why I said " if you do not want your command to be dependant of each other. If you want them to be dependant, then by all means, && is the way to go
    – Yab
    May 19, 2011 at 14:20
2

Separate them with ;, for example

cat somefile.txt; rm anotherfile.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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