1832306 Members
1984 Online
110041 Solutions
New Discussion

ssh remote 'if' command

 
SOLVED
Go to solution
Michael Steele_2
Honored Contributor

ssh remote 'if' command

Hello:

In running remote commands via ssh I've had many successes but not with an if conditional. Can anyone make this work with ssh?

Note: Its not a password problem my authorized_keys file is up to day.


ssh -l $LOGNAME $hostname "if [[ ! -f /etc/profile ]] then
MAX="Number"
fi"

Thanks in advance!
Support Fatherhood - Stop Family Law
6 REPLIES 6
James R. Ferguson
Acclaimed Contributor

Re: ssh remote 'if' command

Hi:

You could do:

# ssh -l ${LOGNAME} ${hostname} -n "[ -f /etc/profile ] && echo 1 || echo 0" > /tmp/returned

...and then examine the value in the '/tmp/returned' file.

Regards!

...JRF...
Steven E. Protter
Exalted Contributor
Solution

Re: ssh remote 'if' command

Shalom,

I think JRF is right, the problem is that the environment is not sourced.

I'd recommend merely calling a script with return value(code to send it) that does this work.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
James R. Ferguson
Acclaimed Contributor

Re: ssh remote 'if' command

Hi (again):

Preventing the local shell from interpolating variables is also very important in situations like this. You may need to use single quotes or escape characters to accommodate your needs.

Consider:

# ssh -l myuser myhost -n 'MAX=0;[ -f /etc/profile ] && MAX=1;echo ${MAX}' > /tmp/returned

...works to return 0 or 1 in the file on the local server.

...whereas:

# ssh -l myuser myhost -n "MAX=0;[ -f /etc/profile ] && MAX=1;echo ${MAX}" > /tmp/returned

...does not.

However, you could do:

# ssh -l myuser myhost -n "MAX=0;[ -f /etc/profile ] && MAX=1;echo \${MAX}" > /tmp/returned

Regards!

...JRF...
Tingli
Esteemed Contributor

Re: ssh remote 'if' command

Or, you can:
ssh -l $LOGNAME $hostname "if [[ ! -f /etc/profile ]] then MAX=Number; fi"
Dennis Handly
Acclaimed Contributor

Re: ssh remote 'if' command

>Tingli: Or, you can:

You need a ";" before the "then".
ssh -l $LOGNAME $hostname "if [[ ! -f /etc/profile ]]; then MAX=Number; fi"

Michael Steele_2
Honored Contributor

Re: ssh remote 'if' command

Well I'm sorry to say that I could not make any of your suggestions work, and ended up following SEP's advice by copying the script over and then executing it remotely.

I think all of you failed to take into consideration the use of the '\' character before special characters like '['. A very important syntax rule when using either ssh or remsh. Except for James, who touched on it, but I could not get James' suggestion to work either.

I will leave this open if anyone wants to continue fiddling with it.

Please trap and paste in your output so I can see the test run successes.

Thanks to you All!
Support Fatherhood - Stop Family Law