Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash redirection with file descriptor or filename in variable

In my script I want to be able to write to either a file or to stdout based on certain conditions. I'm curious as to why this doesn't work in my script:

out=\&1
echo "bird" 1>$out

I tried different combination of quotes, but I keep having a "&1" file created instead of it writing to stdout. What can I do to get this to work how I want?

like image 851
Milo Avatar asked Nov 04 '10 23:11

Milo


1 Answers

A possibly safer alternative to eval is to dup your destination into a temporary file descriptor using exec (file descriptor 3 in this example):

if somecondition; then exec 3> destfile; else exec 3>&1; fi

echo bird >&3
like image 94
Sean Avatar answered Oct 08 '22 17:10

Sean