I am looking for a way to have a bash command be passed default arguments in place of 0 arguments. For example when passing $ls to the command line the user would actually be passing $ls --color to the command line.
1 Answer
You can use functions or aliases.
If you want to prefix all ls invocations with your additional option, you can define an alias like this :
alias ls="ls --color"
This would be like implicitly using the option each time you use ls. When invoked, an alias is replaced by its assigned value. Aliases must be used at the beginning of a command, and the expanded alias will become part of the final statement that will be interpreted. In other words, aliases are a form of automatic text replacement and are quite limited in what they can do.
As suggested by Barmar, you can also use a function, which will allow you to use your default arguments (or some of them) only when no argument at all follows :
ls()
{
if
(( $# )) # True if at least one argument present
then
command ls "$@"
else
command ls --color
fi
}
One thing aliases allow that functions cannot is they execute in the same context as their calling context (they are a form of text replacement, not a function call at all), so they can interact with positional parameters. As an example, you could have an alias like this :
alias shift_and_echo="shift ; echo"
That would actually shift the positional parameters as active where the alias is used, contrary to a function call which would only shift its own arguments and leave the calling context positional parameters unaffected. The echo would have as its arguments whatever follows the alias invocation (which may be nothing at all).
To me, this is the main reason for using aliases in scripts for some specific purposes, as otherwise functions are generally better, being able to receive arguments, contain local variables...
ls, which runs/bin/ls. If it's given arguments it passes them along, otherwise it runs it with your default arguments.less, it uses theLESSenvironment variable to get default options.