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,371 times
2
Chani
- 418
- 2
- 7
- 16
-
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
– Chani Nov 18 '14 at 13:39 -
.bashrc: export A=$PWD; export PROMPT_COMMAND='if [[ $A != "$PWD" ]];then A=$PWD; ls -l $PWD; fi' – Nov 19 '14 at 00:40
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
- 4
-
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