简体   繁体   English

在多个Shell脚本中执行同一命令

[英]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. 并且由于相同的语法属于几种不同的Shell脚本,所以我真的希望它只出现一次。 My first thought was to put it in another shell script: 我的第一个想法是将其放入另一个shell脚本中:

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... 一种解决方案是在shell脚本中定义一个函数。

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. 然后,使用eval稍后对其进行重新评估。

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). 导出LOGFILE变量不起作用的原因是$0$1当时没有有用的值( $0可能是您的Shell的可执行文件,而$1可能什么也不是)。 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. 现在,您以其他方式通过管道传送到tee的任何内容,都将作为参数传递给包装脚本。 For example (assuming it was named new-tee) new-tee java CMD or for testing, new-tee echo "hello world" . 例如(假设它被命名为new-tee) new-tee java CMD或用于测试的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. 在进一步检查了特定的用法之后,我认为我能做的最好的事情就是停止使用bash并升级到更强大的脚本语言(如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. 伊桑(Ethan)的回答确实表明我的问题可以在Bash中解决,但是我建议所有希望做我正在做的事情的人检查他们是否有更简单的方法来完成他们的工作,或者他们的问题可能更好用Python处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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