David
David

Reputation: 328

How to suppress command output safely?

Usually on unix systems you can suppress command output by redirecting STDIN and/or STDERR to a file or /dev/null. But what, if you need to pass content to a piped command via STDIN in a bash script?

The example below should make clear what is meant. It's just an example, though - I'm not searching for a solution to this command in specific but to that kind of situation in general. Sadly there are numerous situations where you would want to suppress output in a script, but need to pass content via STDIN, when a command has no switch to submit the information in an other way.

My "problem" is that I wrote a function to execute commands with proper error handling and in which I would like to redirect all output produced by the executed commands to a log file.

Example problem:

[18:25:35] [V] root@vbox:~# echo 'test' |read -p 'Test Output' TMP &>/dev/null 
[18:25:36] [V] root@vbox:~# echo $TMP

[18:25:36] [V] root@vbox:~# 

Any ideas on how to solve my problem?

Upvotes: 2

Views: 907

Answers (1)

glenn jackman
glenn jackman

Reputation: 247250

What user000001 is saying is that all commands in a bash pipeline are executed in subshells. So, when the subshell handling the read command exits, the $TMP variable disappears too. You have to account for this and either:

  1. avoid subshells (examples given in comment above)
  2. do all your work with variables in the same subshell

    echo test | { read value; echo subshell $value; }; echo parent $value
    
  3. use a different shell

    $ ksh -c 'echo test | { read value; echo subshell $value; }; echo parent $value'
    subshell test
    parent test
    

Upvotes: 4

Related Questions