0

This question already has an answer here:

I was trying to define an alias that helps me to cd to the directory that is created most recently, and I'm using the following in my .bashrc:

alias cdlatest="latestdir=$(ls -td -- */|head -n 1); cd $latestdir"

But this alias only works once. If I change to a new directoy, it still tries to cd to the last directory. It seems becaue the variable $(ls -td -- */|head -n 1) is only evaluated once from the start. How to fix this?

marked as duplicate by Gilles bash Jun 12 '17 at 23:37

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.

  • Wouldn't it be easier to make this a script? Why does it need to be an alias? I suspect, but haven't found a reference yet, that expressions aren't re-evaluated by the alias mechanism. – Joe P Jun 12 '17 at 9:59
  • This may help: stackoverflow.com/questions/13260969/… – Joe P Jun 12 '17 at 10:03
3

Change your double quotes around the alias definition to single and you"re good to go.

alias cdlatest='latestdir=$(ls -td -- */|head -n 1); cd $latestdir'

However, I'd suggest a few streamlining:

alias cdlatest='cd "$(\ls -td -- */|head -n 1)"'

where we do away the intermediate variable "$latestdir", quote the results of the command evaluation $(...), and use an unaliased form of ls.

But you need to remember, that this will not handle files with newlines in their names.

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