在 bash 中动态构建命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1715591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:23:41  来源:igfitidea点击:

Dynamically building a command in bash

bashscripting

提问by Joel

I am construcing a command in bash dynamically. This works fine:

我正在 bash 中动态构建命令。这工作正常:

COMMAND="java myclass"
${COMMAND}

Now I want to dynamically construct a command that redirectes the output:

现在我想动态构建一个重定向输出的命令:

LOG=">> myfile.log 2>&1"
COMMAND="java myclass $LOG"
${COMMAND}

The command still invokes the java process, but the output is not redirected to myfile.log

该命令仍会调用 java 进程,但不会将输出重定向到 myfile.log

Additionally, if I do:

此外,如果我这样做:

BACKGROUND="&"
COMMAND="java myclass $BACKGROUND"
${COMMAND}

The command isn't run in the background.

该命令不在后台运行。

Any clues on how to get the log redirect, and background bits working? (bash -x shows the commands being constructed as expected)

关于如何获得日志重定向和背景位工作的任何线索?(bash -x 显示按预期构造的命令)

(In reality, unlike this example, the values of LOG and BACKGROUND are set dynamically)

(实际上,与本例不同,LOG和BACKGROUND的值是动态设置的)

采纳答案by Aaron Digulla

It doesn't work because quotes disable the special meaning of >and &. You must execute the commands which implement these features of the shell.

它不起作用,因为引号禁用了>and的特殊含义&。您必须执行实现 shell 的这些功能的命令。

To redirect, call exec >> myfile.log 2>&1before the command you want to log.

要重定向,请exec >> myfile.log 2>&1在要记录的命令之前调用。

To run a program in the background, use nohup(nohup cmd args...).

要在后台运行程序,请使用nohup( nohup cmd args...)。

回答by tangens

You could do it with the evalcommand:

您可以使用以下eval命令执行此操作:

eval ${COMMAND}

回答by ezpz

evaldoes what you want.

eval做你想做的。

#!/bin/bash

CMD="echo foo"
OUT="> foo.log"
eval ${CMD} ${OUT}


CMD="sleep 5"
BG="&"
eval ${CMD} ${BG}