dimo414 dimo414 - 4 months ago 7x
Linux Question

Executing The Same Command In Multiple Shell Scripts

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?


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.


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