Search code examples
bashshellstdout

print to stdout by a variable


The following works:

[nir page]$ echo 1 2>&1 >&1
1

But when I use a variable it does not:

[nir page]$ out="&1"
[nir -page]$ echo $out
&1
[nir page]$ echo 1 2>$out >$out
[nir page]$

What am I doing wrong?

Idea is to send output to /dev/null except when I ask to stdout.


Solution

  • What am I doing wrong?

    You are assuming that parts of the syntax can be stored in a variable. They can't. & has to be literally typed on the line, it can't be in a variable.

    Idea is to send output to /dev/null except when I ask to stdout.

    You use file descriptors for that.

    if when I dont ask; then
       exec 1>/dev/null 2>&1
    fi
    echo 1
    

    Or use linux /dev/* files:

    out=/dev/stdout  # or /dev/null
    echo 1 >"$out"