6

I have a few aliases in .bash_aliases. I defined c alias as follows, but it does not work as it should:

...
alias cd='cd; ls -r --time=atime'
alias c='cd'
...

In .bashrc there is a line:

alias ls='clear; ls --color=auto'

Commnand c gives bad output now. It should give the same output as cd; clear; ls -r --time=atime --color=auto.

Other problem: When I type cd dir I should stay in dir but I'm in $HOME as a result.

How can I solve this and improve in defining aliases? Is .bash_aliases interpreted as a regular grammar?

tshepang
  • 64,472
  • 86
  • 223
  • 290
xralf
  • 16,149
  • 29
  • 101
  • 149

2 Answers2

9

Use functions instead, the advantage being the possibility to pass parameters and a cleaner syntax.

function cd() {
  command cd "$@"
  ls -r --time=atime
}

function c() {
 cd "$@"
}

function ls() {
  clear
  command ls --color=auto "$@"
}

(command is a bash builtin used to refer to the real command, and not functions with the same name).

enzotib
  • 50,671
  • 14
  • 120
  • 105
  • `command cd` will give you `command not found: cd`, you meant `builtin cd`. – Stéphane Gimenez Sep 01 '11 at 16:44
  • @Stéphane Gimenez: are you sure? it works here – enzotib Sep 01 '11 at 16:46
  • Seems that `bash` strangely accepts it. `zsh` doesn't… and `dash` don't know about `builtin`… what a mess. – Stéphane Gimenez Sep 01 '11 at 16:48
  • 1
    @StéphaneGimenez The [`command`](http://pubs.opengroup.org/onlinepubs/009695399/utilities/command.html) utility suppresses alias and function lookup only. It also has an effect on special built-ins (see the spec for details). `command cd` should always run the build-in. Zsh is non-standard by default, you need to set the `posix_builtins` option to make it behave according to the standard. – Gilles 'SO- stop being evil' Sep 01 '11 at 23:21
4

c should be exactly equivalent to cd. I expect you'll see the same error from cd dir as from c dir, and that c alone works.

cd won't work the way you've defined it, because aliases perform a simple text substitution. cd dir is expanded to cd; ls -r --time=atime dir. Aliases are pretty much limited to giving a command a shorter name or providing default options, e.g. alias c=cd or alias cp='cp -i'. For anything more complex, such as running several commands, use a function.

cd () {
  command cd "$@" &&
  ls -r --time=atime
}

See also Aliases vs functions vs scripts, How to pass parameters to an alias?.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • Thank you. You're right `c` and `cd` makes no difference. I will accept enzotib answer because it's larger, but your answer gives me the feeling of understanding and the ability to accept his answer. So it belongs to accepted too. – xralf Sep 02 '11 at 12:04