12

$SSH_CLIENT has IP address with some port info, and echo $SSH_CLIENT gives me '10.0.40.177 52335 22', and Running

if [ -n "$SSH_CONNECTION" ] ; then for i in $SSH_CLIENT do echo $i done fi

gives me

  • 10.0.40.177
  • 52335
  • 22

And I see the first element is the IP address.

Q : How can I get the first element of $SSH_CLIENT? ${SSH_CLIENT[0]} doesn't work.

0

6 Answers 6

29
sshvars=($SSH_CLIENT) echo "${sshvars[0]}" 

or:

echo "${SSH_CLIENT%% *}" 
Sign up to request clarification or add additional context in comments.

2 Comments

For the clueless (like me) the second is doing “parameter substitution.” Here's a reference: tldp.org/LDP/abs/html/parameter-substitution.html
or echo ${SSH_CLIENT// *}
8

you can use set -- eg

$ SSH_CLIENT="10.0.40.177 52335 22" $ set -- $SSH_CLIENT $ echo $1 # first "element" 10.0.40.177 $ echo $2 # second "element" 52335 $ echo $3 22 

Comments

3

For strings, as is the case here, the <<< operator may be used:

$ read ipaddress outport inport <<< $SSH_CLIENT 

See e.g: Linux Bash: Multiple variable assignment. Don't do this with binary input though: Is there a binary safe <<< in bash?

2 Comments

There's no reason to do $(echo ...), it's the same as just including the variable.
Right you are. Fixed.
1

If you prefer awk:

$ SSH_CLIENT="10.0.40.177 52335 22" $ echo $SSH_CLIENT|awk '{print $1}' # first element 10.0.40.177 $ echo $SSH_CLIENT|awk '{print $2}' # second element 52335 $ echo $SSH_CLIENT|awk '{print $3}' # third element 22 

Comments

0

I use this in my .bash_profile, and it works beautifully.

if [ -n "$SSH_CONNECTION" ] ; then echo $SSH_CLIENT | awk '{print $1}' fi 

Comments

-1

You can get it programmatic way via ssh library (https://code.google.com/p/sshxcute)

public static String getIpAddress() throws TaskExecFailException{ ConnBean cb = new ConnBean(host, username, password); SSHExec ssh = SSHExec.getInstance(cb); ssh.connect(); CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\""); String Result = ssh.exec(sampleTask).sysout; ssh.disconnect(); return Result; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.