3

I want to use a variable from the main shell in a sub shell. I did:

export mysql_root_password="test"
(
    echo $mysql_root_password
) | dialog --gauge "Working hard..." 6 50

There is no output. Of course there is not since I send the output to dialog. Is there a way to output specific variables still the normal way without removing the dialog part?

Braiam
  • 35,991

3 Answers3

3

If your system/shell supports it, you can use redirection and process substitution to output stuff to different file descriptors. For example:

(
    echo "This goes to fd 1"
    echo "This goes to fd 3" >&3
) 3> /dev/tty | some command

In this example, the first echo statement is sent to some command, while the second is sent to the terminal.

(
    echo "This goes to fd 1"
    echo "This goes to fd 3" >&3
) 3> >(some command)

In this case, the first echo statement goes to stdout, and the second echo statement goes to some command.

augurar
  • 621
2

You could (and probably should) print your debug messages on the script's standard error stream instead of its standard output. The standard error isn't going through the pipe, so all is well.

(
    echo >&2 "$mysql_root_password"
) | dialog --gauge "Working hard..." 6 50

If you really need the message on the script's standard output, you can open an additional file descriptor that's connected to the script's standard output, and redirect the message to that file descriptor.

{
  (
      echo >&3 "$mysql_root_password"
  ) | dialog --gauge "Working hard..." 6 50
} 3>&1

For more information, see When would you use an additional file descriptor? and the posts it links to.

1

You could echo the value of mysql_root_password to stderr, if seeing that value is only diagnostic:

echo $mysql_root_password >&2

You could also maybe use tee:

export mysql_root_password="test"
(
    echo $mysql_root_password
) | tee /dev/tty | dialog --gauge "Working hard..." 6 50

I hesitate to reccommend tee as sometimes it (or the pipes) do buffering that causes the output to be less than useful.