views:

173

answers:

4

I'm using the following to to tee output of a command into a file:

logs/`basename $0`-`basename $1`.`date +%F--%R\`.log

And since this same syntax belongs in several different shell scripts, I'd really like it to only appear once. My first thought was to put it in another shell script:

export LOGFILE=logs/`basename $0`-`basename $1`.`date +%F--%R`.log
# OR
export LOGFILE=logs/\`basename $0\`-\`basename $1\`.\`date +%F--%R\`.log

And have each file call the command like this:

java CMD | tee $LOGFILE

However this doesn't work. Is there any way to describe a file to create in the way you see above only once but be able to reference it repeatedly in scripts?

+1  A: 

If your shell supports defining functions (e.g., bash, korn, etc.) then you could put it in a function and have each script include/import/whatever that file that the function is in.

lumpynose
A: 

The reason that exporting the LOGFILE variable does not work, is that $0 and $1 don't have useful values at that point ($0 is probably your shell's executable, and $1 is probably nothing). One possibility would be a wrapper script like this:

#!/bin/sh
LOGFILE="logs/`basename $0`-`basename $1`.`date +%F--%R`.log"
"$@" | tee "$LOGFILE"

Anything that you would otherwise pipe to tee, you now pass as arguments to the wrapper script. For example (assuming it was named new-tee) new-tee java CMD or for testing, new-tee echo "hello world".

Adam Batkin
+2  A: 

One solution is to define a function in the shell script...

But you almost have it working with the export. If you want to keep going with that, the key is to escape out the $'s so they don't get replaced with their values until you're ready. Then use eval to re-evaluate it later.

E.g.:

501 ~$ export foo='$bar'
502 ~$ echo $foo
$bar
503 ~$ export bar=moo
504 ~$ eval echo $foo
moo
505 ~$ export bar=hello
506 ~$ eval echo $foo
hello
Ethan
A: 

After examining my specific curcumstances further, I think the best thing I can do is stop using bash and upgrade to a more powerful scripting language like python. Ethan's answer does indicate my problem can be resolved in bash, but I would suggest to anyone looking to do what I'm doing that they examine if there's not a simpler way to do what they're doing, or if their problem might be better handled in Python.

dimo414
Or perl, or ruby, etc. I'm an old fart and like the challenge of shell scripts.
lumpynose