Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

4 Answers 4

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 "$@"; }
share|improve this answer

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.

share|improve this answer

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'

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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