2

Lets say I want to do cd home and then ls -lrth. I want these two things combined into a single command. I tried writing an alias, but it didnt work. Can you help me ?

Chani
  • 418

1 Answers1

2

If you are using bash try to put this in your bashrc/bash_profile:

alias cd='cd $1 && ls -lrth'

UPDATE:

This is not correct, i just double checked it, it is just listing the dir you did want to cd in but it stays in your actual dir where you launched the command.

UPDATE 2:

You have to create a bash function instead of an alias it is much safer than overriding a built in command.

cdd() {
     cd "$1" && ls -lhtr;
}

This should work.

APSy
  • 36
  • Yep. Even the bash man page itself recommends using functions instead of aliases. Aliases should only be used for the simplest things. My rule of thumb when creating aliases: "If at first you don't succeed, give up and write a function." :) – PM 2Ring Nov 18 '14 at 14:05
  • And if you want to call the function cd (which I don't recommend), you can do cd(){ command cd "$1";ls -lrth; }. The command builtin suppresses shell function lookup, so the function doesn't die in a recursive death spiral. – PM 2Ring Nov 18 '14 at 14:07
  • Ah good to know i never gave a function the same name like a built in because i was not sure what would happen and i was too afraid to test ;) – APSy Nov 18 '14 at 14:10
  • 1
    :) Definitely don't test stuff like that in your ~/.bashrc, do it in a shell so it'll die when you reboot. – PM 2Ring Nov 18 '14 at 14:13
  • Oops! I just noticed I accidentally put ; instead of && in my example. It should be cd(){ command cd "$1" && ls -lrth; } – PM 2Ring Nov 18 '14 at 14:17