How to get the for loop output from a remote server in UNIX shell scripting?

Hi,

I am using ksh , when i try to use for loop i am getting the expected output.

$for variable in $(ps -fu user | grep -i something/ | grep -i something | grep -v grep | awk '{print $2}');do
> grep $variable /tmp/some_path/*/*
> done

when tried the below to remote server, getting the entire content rather than the expected output.

$for variable in $(ssh server_name "ps -fu user | grep -i something/ | grep -i something | grep -v grep | awk '{print $2}'");do
> grep $variable /tmp/some_path/*/*
> done

I tried the below to remote server , but getting the below error.

$ssh server_name "for variable in $(ps -fu user | grep -i something/ | grep -i something | grep -v grep | awk '{print $2}');do
> grep $variable /tmp/some_path/*/*;
> done"
/bin/ksh: syntax error at line 2: `31656' unexpected

I am not sure what is the syntax mistake i did in the above script.

Please advise.

Thanks,
Regards,
karthikram

If you have pgrep then you can probably do

pgrep -u user something

and no problem to run that as ssh argument.
If you insist in your complex commands, save them in a script command.sh
And run it remotely with

ssh -qx server_name ksh < command.sh

By passing via a stream the script commands are only interpreted by one shell (the ksh at the remote server).

1 Like

Thanks you very much , i came across pgrep many times but it didnt strick.

I am able to learn that if we need to run such kind of script better to save and run.

By passing via a stream the script commands are only interpreted by one shell (the ksh at the remote server).

Thanks,
Regards,
karthikram

You'll need to fiddle around with some serious escaping, like (and eventually more)

$ssh server_name 'for variable in $(ps -fu user | grep -i something/ | grep -i something | grep -v grep | awk "{print\ \$2}");do  grep "$variable" /tmp/some_path/*/*; done'
1 Like

Thank you very much , you are all great, it worked perfectly.

i made only this change to work in ksh

$ssh server_name 'for variable in $(ps -fu user | grep -i something/ | grep -i something | grep -v grep | awk "{print \$2}");do  grep "$variable" /tmp/some_path/*/*; done'

Thanks,
Regards,
karthikram