Bash script redirection not working, why?

I recently discovered unexpected behavior in a bash script, and I would like to understand this before I get around it. Here's a simplified example:

#! /bin/sh
SCRIPT="/tmp/echoscript.sh >> /tmp/log"
/bin/sh ${SCRIPT}

echoscript.sh just executes 'echo "abc"'

Unexpectedly, 'abc' is sent to the terminal, and not to the / tmp / log file. Why is this?

If I changed the third line to:

/bin/sh ${SCRIPT} >> /tmp/log

Then I get the expected result; 'abc' goes to the log file.

+4
source share
4 answers

You cannot redirect such variables. When you execute Bash interprets /bin/sh ${SCRIPT}as if you wrote:

/bin/sh "/tmp/echoscript.sh" ">>" "/tmp/log"

, ">>" , . - , Bash , . .

+3

, (, ). , .

, eval:

eval "/bin/sh ${SCRIPT}"
+4

, , ${ SCRIPT}. /bin/sh: /tmp/echoscript.sh >> /tmp/log: No such file or directory.

You will need to tell the shell to evaluate $ {SCRIPT} before running it, for example:

eval /bin/sh ${SCRIPT}
$ cat /tmp/log
abc
+1
source

another way:

alias SCRIPT="/bin/sh /tmp/echoscript.sh >> /tmp/log"
SCRIPT
+1
source

All Articles