2

How do you create a bash alias for a command with flags? For example, if I run ls -l, I want that to alias to ls -a.

This doesn't work: alias "ls -l"="ls -a"

Another example: If I type reboot now, I want that to simply run reboot.

Would bash functions be useful here?


EDIT: Sorry for the silly ls -l example. This is what I really want: if you executed reboot now, I want it to actually execute reboot. This is why.

  • 3
    The real question is why? Why bother typing ls -l if you want ls -a? – jw013 Apr 11 '14 at 20:33
  • True, that was a silly example. The real reason is that on recent versions of Ubuntu, the command reboot now takes the machine down for maintenance, which is bad if you're SSHed into a remote VM and can't manually reboot it. I wanted to intercept all reboot now commands and change them to reboot. – Kevin Boos Apr 12 '14 at 00:46

3 Answers3

5

Another example: If I type reboot now, I want that to simply run reboot.

Create a function:

reboot() {
  command reboot
}

Now invoking the command reboot would invoke the function reboot which would ignore all parameters passed to it.

That is:

reboot

and

reboot now

would execute the command reboot (without any argument).

devnull
  • 10,691
4

You should just alias ls:

alias ls='ls -a'

after that, if you do ls -l it will result in ls -la

Anthon
  • 79,293
  • Thanks, I understand that. Maybe I shouldn't have used such a simplistic example. I'd like to know how (or if it's possible) to alias a general command with given flags or arguments. – Kevin Boos Apr 12 '14 at 00:47
3

This is what I really want: if you executed reboot now, I want it to actually execute reboot.

Find out the absolute path of reboot (e.g., via whereis reboot). Make sure /usr/local/bin is in $PATH before that (it probably is already).1 Now create a /usr/local/sbin/reboot file that looks like this:

#!/bin/sh

reboot

That should be owned by root and chmod 755 /usr/local/bin/reboot. From now on, by default

reboot whatever, blah-blah 

will just invoke reboot with no arguments.

1. If not, see this Q&A.

goldilocks
  • 87,661
  • 30
  • 204
  • 262