Joel
Joel

Reputation: 30146

Dynamically building a command in bash

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

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

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)

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

Upvotes: 24

Views: 27930

Answers (3)

ezpz
ezpz

Reputation: 12027

eval does what you want.

#!/bin/bash

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


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

Upvotes: 19

tangens
tangens

Reputation: 39733

You could do it with the eval command:

eval ${COMMAND}

Upvotes: 24

Aaron Digulla
Aaron Digulla

Reputation: 328556

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

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

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

Upvotes: 9

Related Questions