2

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.

3
  • You can write a function called ls, which runs /bin/ls. If it's given arguments it passes them along, otherwise it runs it with your default arguments. Commented Mar 3, 2017 at 2:33
  • Some commands look in an environment variable for default settings. Check the documentation of the commands you're interested in doing this with. Commented Mar 3, 2017 at 2:39
  • An example is less, it uses the LESS environment variable to get default options. Commented Mar 3, 2017 at 2:40

1 Answer 1

4

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...

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

2 Comments

That ls function calls itself repeatedly and crashes.
Nasty and obvious bug! The updated version should avoid the recursive calls.

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.