8

I have a ~/bin directory (which is on my PATH) where I store a lot of little 1 or 2 line scripts. Some of them just cd into a directory and run a command on a file, like vim or something. But I also have a lot of aliases in my .bash_aliases file which serve the same purpose.

How do you decide between writing a little bash script and writing an alias? Does it matter at all which way you go?

dan
  • 4,077
  • 5
  • 27
  • 34

4 Answers4

5

If I use them frequently enough to warrant the overhead of having them loaded up in every shell. I will write them up as functions.

If they are project specific, I might write them up as a set of aliases and functions that can be sourced into a shell when I'm working on that project.

Only if they work in a stand-alone fashion does anything get made into a script in my ~/bin. There are some one liners that are basically aliases, but these are for running from places other than shells (run prompts in other programs for example). For the most part they have to be pretty substantial scripts.

Caleb
  • 70,105
1

In general shell script functions are more flexible than aliases and you should prefer them. For example in an alias you cannot test if the number of arguments given or their types are the expected. I agree with Caleb that aliases fit well with simple one liners, for example alias cp='cp -i'

sakisk
  • 2,873
1

For anything more complicated a string substitution of a single command, a script is probably more appropriate. Also, anything that will be used by other scripts or might be used by other people are probably better off as scripts. While running programs out of someone else's bin directory is not a great idea, it's better than sourcing someone's individual aliases file.

Aliases are best for personalizing your interactive environment. For example, e='emacs -nw', and that sort of thing.

Goladus
  • 11
0

I use the simplest possible approach.

Mainly, if the command has no parameters, I usually use aliases.

If the command has parameters I use a function.

e.g. making and cd'ing to a directory:

md () { [ $# = 1 ] && mkdir -p "$@" && cd "$@" || echo "Error - no directory passed!"; }

I also use a function if the command uses an installed function that itself has params

for example, adding -v to git:

git () { [ $1 = commit ] && command git commit -v "${@:2}" || command git "$@"; }