-1

I'm trying to retrieve the code return from this script:

#!/bin/bash
echo "CM  1"
ssh -i key/keyId.ppk [email protected] "
grep blabla ddd
if [ ! $? -eq 0 ]; then exit 1; fi
"
echo $?

But the last command echo $? returns 0 instead of 1.

And if try to run separately (not as a script) :

  • the ssh command: ssh -i key/keyId.ppk [email protected]
  • grep blabla ddd => I get the msg "grep: ddd: No such file or directory"
  • then: if [ ! $? -eq 0 ]; then exit 1; fi
  • then: echo $? => it returns 1 as expected

Do you have an idea why it doesn't work in my script ?

Thank you

4
  • what does it mean "returns nothing"? What version are you using? It works fine for me. Commented Apr 19, 2016 at 19:06
  • What is the reason behind the use of ssh's -t ? Commented Apr 19, 2016 at 19:12
  • @Rany Albeg Wein : there was no special reason for the -t Commented Apr 19, 2016 at 19:56
  • @Jakuje : GNU bash, version 4.1.17(0)-release (i686-pc-cygwin) I've edited my post, you are right it works in my1st version, but in this current version it doesn't work for me Commented Apr 19, 2016 at 20:02

1 Answer 1

1

This code

ssh -i key/keyId.ppk [email protected] "
grep blabla ddd
if [ ! $? -eq 0 ]; then exit 1; fi
"

evaluates $? in your shell and not in the remote one, because the $ is not escaped in single quotes. You should escape that to reach desired behaviour. Once to avoid evaluation in your local shell, for the second time to avoid evaluation when it is passed to the bash on remote side. Or rather put the command into single quotes:

ssh -i key/keyId.ppk [email protected] '
grep blabla ddd
if [ ! $? -eq 0 ]; then exit 1; fi
'
Sign up to request clarification or add additional context in comments.

2 Comments

Also, comparing an exit status to 0 is what the if command does already! You don't need to use [ and $?. if ! grep blabla ddd is equivalent.
@WumpusQ.Wumbley True. But I didn't want to spoil his algorithm :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.