简体   繁体   中英

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.

Eg:

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

如果您的外壳支持定义函数(例如bash,korn等),则可以将其放入函数中,并让每个脚本包括/导入/该函数所在的文件。

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" .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM