I have some script to be executed on remote server(server-2) through ssh from server-1 and I have to write that output into a log file named file.log on server-1.

I am trying this: sc.sh

echo 'testing'
cp $HOME/dir1/file1 $HOME/dir2

Now, executing the sc.sh through ssh:

sshpass -p 'psswd' ssh username@server-2 "bash -s" < sc.sh | tee -a file.log
if [ $? -eq 0]; then
  echo "successfully executed the script file"
  echo "failed copying due to incorrect path"

Now because of tee -a file.log command, it will always return 0 even though my commands in script file fails. How can I write into log file and should check the if condition after ssh command which should work based on the ssh commands exit code?

  • In case you are using bash, see man bash -> PIPESTATUS. Also see pipefail.
    – rudimeier
    Commented May 15, 2017 at 6:48

2 Answers 2


checking ${PIPESTATUS[0]} worked for me...

if [ ${PIPESTATUS[0]} -eq 0 ]; then
  echo "successfull"

echo ${PIPESTATUS[*]} prints the exit codes of all the pipeline commands.


The answer to : "how to log the output of ssh shell?" is

  • use a simple redirect >


ssh user@remote_host "command" > local_log_file.txt


sshpass -p 'psswd' ssh username@server-2 "echo 'testing'; cp dir1/file1 dir2;" > local_machine_ssh_log.txt

If you want to check the result of the cp cmmand on the remote server, I'd suggest running the if statement on the remote host as part of the command you send, immediately after running the cp command

something like:

sshpass -p 'psswd' ssh username@server-2 "echo 'testing'; cp dir1/file1 dir2;if [ $? -eq 0 ]; then   echo "successfully copied"; else   echo "failed copying due to incorrect path"; fi" > local_machine_ssh_log.txt
  • But i have few commands to run on this server-1 immediately after cp command. Commented May 15, 2017 at 6:19
  • @EjjagiriVenkatesh - what exactly would you like to do, and check using the if statement?
    – Yaron
    Commented May 15, 2017 at 6:24
  • in the place of commands i have to send a script file sometimes to execute, in that case how can we check. I have to check if all the commands in the sent script file are executed successfully or not? How can i check and log the output? Commented May 15, 2017 at 6:26
  • @EjjagiriVenkatesh - can you check the local_output.txt file in your local machine?
    – Yaron
    Commented May 15, 2017 at 6:28
  • edited my question, can you please give me solution for this? Commented May 15, 2017 at 6:32

You must log in to answer this question.

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