Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash command output not saving to text file or variable [duplicate]

Tags:

bash

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 [email protected] > 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).

like image 921
adamconkey Avatar asked Mar 07 '18 21:03

adamconkey


People also ask

How do I save a terminal output to a text file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do I redirect console output to a file?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

How do you save the output of a command in a variable?

Here are the different ways to store the output of a command in shell script. You can also use these commands on terminal to store command outputs in shell variables. variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name=`command` variable_name=`command [option ...]


2 Answers

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.

like image 163
0x5453 Avatar answered Sep 19 '22 17:09

0x5453


Try this:

ssh [email protected] > 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"

like image 41
A. Kendall Avatar answered Sep 18 '22 17:09

A. Kendall