Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: cached command result in alias?

I have a alias in bash look like this:

alias bblog="ssh -t  bbdev tail -f /var/logs/bb/stdout-stderr-`date \"+%Y%m%d\"`.log"

It works fine except when the clock turns to the following day, (pass midnight), I have to rerun the bblog to tail the next log. But date \"+%Y%m%d\" still returns the previous date. It seems cached the value. So it still tailing the previous log.

Any ideas? Thanks

like image 572
compass Avatar asked Apr 26 '13 09:04

compass


2 Answers

put the alias in single quotation marks, this suppresses the backtick evaluation until use time.

alias bblog='ssh -t  bbdev tail -f /var/logs/bb/stdout-stderr-`date "+%Y%m%d"`.log'

I'd recommend using $() instead of backticks as it's easier to understand the logic.

a simpler example of it's use is:

alias foo='echo $(date)'

argle:~$ foo
Fri Apr 26 10:29:14 IST 2013
argle:~$ foo
Fri Apr 26 10:29:15 IST 2013
like image 95
Petesh Avatar answered Oct 09 '22 13:10

Petesh


Replace your alias with a shell function:

bblog () {
    ssh -t bbdev tail -f /var/logs/bb/stdout-stderr-$(date "+%Y%m%d").log
}

This defers the call to date until when you actually run the function, making the quoting simpler. It is also more flexible, allowing you to pass arguments should the need arise. For example, you could specify an alternate host to log into:

bblog () {
    host=${1:-bbdev}
    ssh -t "$host" tail -f /var/logs/bb/stdout-stderr-$(date "+%Y%m%d").log
}

$ bblog          # Check bbdev
$ bblog bother   # Check a different host
like image 39
chepner Avatar answered Oct 09 '22 14:10

chepner