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
  • 65,642
xralf
  • 15,415

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
  • 51,661
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?.

  • 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