aswin aswin - 1 year ago 102
Bash Question

Execute commands one by one in .aliases file in bash

I would like to create an alias in bash where if I type 'logs' it should take me to the latest log file. My folder is structured such that ~/logs/date/time. After googling for sometime I found out the below command and it is working fine if i give in the bash prompt

cd ~/logs && cd `ls -tr | tail -1` && cd `ls -tr | tail -1`

But if I add it .aliases and map it to 'logs' then it is not working as expected. It cd's into logs and then try cd into latest file/folder where i execute the command. (For eg.) if I am in FOLDER1 and execute 'logs', it
cd's into logs and then try to cd into latest folder in FOLDER1.

Edited: My alias definition

alias logs="cd ~/logs && cd `ls -tr | tail -1` && cd `ls -tr | tail -1`"

Any idea why it is behaving like this & how can I make this work ?

Answer Source

The problem is that backquoted commands are evaluated at once when defining the alias.

Either escape them:

alias logs="cd ~/logs && cd \`ls -tr | tail -1\` && cd \`ls -tr | tail -1\`"

Or a function, that works too and is more readable, so you can add robustness more easily as Charles suggested (when creating an alias, you just do a quick & hack job):

     cd ~/logs || return
     cd "`ls -tr | tail -1`" || return
     cd "`ls -tr | tail -1`" || return
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download