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?

2
  • Define "bad output". What does it do, and what did you expect it to do?
    – cjm
    Sep 1, 2011 at 16:21
  • see question edit.
    – xralf
    Sep 1, 2011 at 16:37

2 Answers 2

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

4
  • command cd will give you command not found: cd, you meant builtin cd. Sep 1, 2011 at 16:44
  • @Stéphane Gimenez: are you sure? it works here
    – enzotib
    Sep 1, 2011 at 16:46
  • Seems that bash strangely accepts it. zsh doesn't… and dash don't know about builtin… what a mess. Sep 1, 2011 at 16:48
  • 1
    @StéphaneGimenez The command 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. Sep 1, 2011 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?.

1
  • 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 2, 2011 at 12:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .