0

This question already has an answer here:

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 ?

marked as duplicate by don_crissti, jimmij, Ramesh, Karlson, Anthon Nov 18 '14 at 20:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Can you show us alias you tried but it didn't work? – Arkadiusz Drabczyk Nov 18 '14 at 13:31
  • alias cd='cd; ls -lrth' didnt work :( – Chani Nov 18 '14 at 13:33
  • It works for me. It changes directory to ~ and executes ls -lrth. What shell do you use? – Arkadiusz Drabczyk Nov 18 '14 at 13:35
  • Bash. It tells me 'ls - cannot stat <directory name> – Chani Nov 18 '14 at 13:39
  • .bashrc: export A=$PWD; export PROMPT_COMMAND='if [[ $A != "$PWD" ]];then A=$PWD; ls -l $PWD; fi' – DarkHeart Nov 19 '14 at 0:40
1

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.

  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.