Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop an infinite recursion in a Bash Script

Tags:

bash

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!

like image 296
mljohns89 Avatar asked Mar 16 '23 15:03

mljohns89


1 Answers

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.

like image 138
Etan Reisner Avatar answered Mar 23 '23 22:03

Etan Reisner