7

I am seeing strange behavior when trying to store the output of an SSH check to see if I have SSH access to an account. I tried the following:

ssh git@bitbucket.org > temp.txt

and I expect a string message telling me if permission was denied or not to be saved to temp.txt. But the output goes straight to the terminal and isn't saved to file. But, if I do

ls -l > temp.txt

that output is saved to file. What could be causing this difference in behavior? I'm ultimately going to be saving the output to a variable but see similar behavior for that case as well. I'm on Ubuntu 16.04 bash version 4.3.48(1).

adamconkey
  • 4,104
  • 5
  • 32
  • 61
  • 1
    Since "permission denied" is typically considered an error, is the output being routed to stderr instead of stdout? If so, you need to use `2> temp.txt` or `> temp.txt 2>&1`. – 0x5453 Mar 07 '18 at 21:25
  • @0x5453 I think you're right, that's what I needed to do, and in fact that's in the link I posted I just didn't understand what that syntax meant. Also on a different machine it was working, so it seemed system dependent. Can you write as answer? I'll mark accepted. – adamconkey Mar 07 '18 at 21:29

2 Answers2

5

Since "permission denied" is typically considered an error, is the output being routed to stderr instead of stdout? If so, you need to use 2> temp.txt or > temp.txt 2>&1.

More information:

On many systems, program output is broken up into multiple streams, most commonly stdout (standard output) and stderr (standard error). When you use >, that only redirects stdout, but 2> can be used to redirect stderr. (This is useful if you want normal output and errors to go to two different files.)

The syntax 2>&1 means "take all output on stderr and redirect it to stdout", so your file would contain output from both streams.

0x5453
  • 12,753
  • 1
  • 32
  • 61
2

Try this:

ssh git@bitbucket.org > temp.txt 2>&1

Basically what this does it tells linux to redirect stderr (2) to stdout (&1), and then redirect stdout to your file "temp.txt"

A. Kendall
  • 391
  • 3
  • 12