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 ?
Asked
Active
Viewed 4,658 times
2

Chani
- 418
1 Answers
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 docd(){ command cd "$1";ls -lrth; }
. Thecommand
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 becd(){ command cd "$1" && ls -lrth; }
– PM 2Ring Nov 18 '14 at 14:17
~
and executesls -lrth
. What shell do you use? – Arkadiusz Drabczyk Nov 18 '14 at 13:35