My script does a lot of remote calls and output progress of a long operation on screen to STDOUT. I currently hide all of STDOUT and STDERR from my remote calls because i don'T want them to taint my STDOUT and STDERR.

How would one allow logging or redirecting of STDOUT and STDERR from the remote calls using "ssh" to be available to whoever is calling my script. I've heard of file descriptors but i can't seem to understand how to implement them.

I've seen a lot of posts on file descriptors but never in the optic of providing or redirecting output like this so i'm a little lost!

Edit #1

So i have this code right now to execute remote calls based on a previously set variable. If i do the following:

remoteCall() {

        command exec 1>&3
        command exec 2>&4
        ${remoteCommand} $@
    ) &> /dev/null


It should hide the output and error from that remote call unless i redirect 3/4 to 1/2. So if someone calls my script in the grand scheme of thins (much bigger than this example), we should never see anything output to screen except what i echo to STDOUT or STDERR.

If i wanted to use the STDOUT of the remoteCall such as in this example:

result=$(remoteCall "sudo lvs -o LV_NAME "${1}" --noheadings | wc -l")

Would i have to do it that way?

result=$(remoteCall "sudo lvs -o LV_NAME "${1}" --noheadings | wc -l" 3>1)

So that result contain the number of lines?

1 Answer 1


If you do in your script:

ssh host cmd >&3 2>&4

Then whomever calls your script can do:

your-script > output 2> error 3> remote-output 4> remote-error

However, if they don't redirect fds 3 or 4, the >&3 redirection will cause a 3: Bad file descriptor fatal error.

You could default to redirecting those to /dev/null in that case with something like:

   command exec >&3
   command exec 2>&4
   exec ssh host cmd...
) > /dev/null 2>&1

Running the exec special builtin under command cancels the special effect that it exits the subshell upon a failed redirection. The errors for those failed redirections are conveniently discarded by the outer > /dev/null 2>&1.

  • Can you complement based on my edit thanks! Jul 24, 2017 at 18:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .