4

So I've fallen into this classic trap. While trying to teach myself some basic bash scripting, I decided that I wanted to do this:

alias emacs=emacsFunction

emacsFunction() {
    if [ "$#" -eq 1 ]; then
        emacs $1 &
    fi
    emacs 
}

The goal is pretty simple. When I type emacs into the Terminal, if I supply an argument (e.g. emacs .bashrc), I want it to open my .bashrc file in emacs and still allow me to input commands in my terminal window (adding '&' to a command allows this).

I'm open to any and all suggestions. I'm sure that there is a way more efficient (smarter) way to do this than the code I have here.

Thanks in advance!

2
  • Where did you put this code? What happened? Commented Jun 23, 2015 at 21:31
  • This is in my .bashrc file. When I try calling "emacs .bashrc" or any emacs ???, it falls into an infinite recursion. Commented Jun 23, 2015 at 21:32

2 Answers 2

7

Avoiding functions/aliases/etc. is what the command builtin is for (see Bash Builtin Commands). So use command emacs when you want to avoid your function or alias.

That being said you don't need both the function and the alias here. Your function can just be called emacs.

You also don't need to explicitly test for arguments unless you only want it to go to the background when you pass arguments (and don't otherwise). (I assume in the background case it spawns an X window?)

If you do want the background-only-for-arguments version then you want this:

emacs() {
    if [ $# -eq 0 ]; then
        command emacs
    else
        command emacs "$@" &
    fi
}

Assuming you don't need the background-only-for-arguments business then you can just use:

emacs() {
    command emacs "$@" &
}

That being said if you don't want the background-only-for-arguments behavior then this isn't really any different then just always running emacs & or emacs <files> & since you only save typing the & at the end.

Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect! Thank you so much! Just a quick question, do you have any links you could recommend please that would give me an introduction to these features (such as command). The only one I know about is: gnu.org/software/bash/manual/bashref.html#Bash-Features
Not really. The reference manual is good (and should list command). The Bash Guide is good. The Bash FAQ is good too.
1

Switching to if..else should help:

alias emacs=emacsFunction

function emacsFunction () {
    if [ "$#" -eq 1 ]; then
        emacs $1 &
    else
        emacs
    fi
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.