String / array in bash?

I want to do something like this in bash (.bashrc) so that the alias is set based on which comp the user is logged into. I don’t know how to get 210 out of 10.0.0.210, and then the way to go through the list "user = xxx" is better

$radek ='210'
$mike ='209'


#SSH_CLIENT='10.0.0.210 53039 22'  <--- system variable
$user = based on the 4th part of IP so 
   $user = radek if 210
   $user = mike if 209

alias sites='cd /var/lib/code/'+$user

, so the final alias looks like g

'cd / var / lib / code / radek ' if it is registered on 210 computer

'cd / var / lib / code / mike ' if it is registered on a 209 computer


Final code thanks to @Dennis Williamson

users[210]=radek
users[209]=mike

octet=($SSH_CLIENT)    # split the value on spaces
#octed=${octet[0]##*.}        # extract the last octet from the ip address
alias sites='cd /var/lib/code/'${users[${octet[0]##*.}]}
+3
source share
3 answers

Try:

users[210]=radek
users[209]=mike

octet=($SSH_CLIENT)    # split the value on spaces
octet=${octet[0]##*.}  # extract the last octet from the ip address
alias sites='cd /var/lib/code/'${user[octet]}

Another way to assign users:

names=(bob jim anne kelly rick)
octet=211
for name in ${names[@]}
do
    users[octet++]=$name
    if (( octet > 255 ))
    then
        echo "Error: range limit exceeded"
        break
    fi
done
+3

:

export user=`env|grep -i SSH_CLIENT|cut -d' ' -f1|cut -d'.' -f4`

+ .

alias sites='cd /var/lib/code/'$user

, , :

temp_user=`env|grep -i SSH_CLIENT|cut -d' ' -f1|cut -d'.' -f4`
user=`env|awk -F= "/=$temp_user/"'{print $1}'`
+1

If you do not have a strict format requirement for storing the user for ip mapping, the following example script will be used:

user_210="radek"
user_209="mike"

function define_alias
{
        local ip_last_part=`echo $1 | cut -d ' ' -f1 | cut -d '.' -f4`
        eval user=$`echo "user_$ip_last_part"`
        echo "User '$user' identified for ip ending in '$ip_last_part'"
        alias sites="cd /var/lib/code/$user"
        echo "Alias defined : `alias sites`"
}


#Exampe usage :

# will come from env
export SSH_CLIENT='10.0.0.210 53039 22'
define_alias $SSH_CLIENT


export SSH_CLIENT='10.0.0.209 53039 22'
define_alias $SSH_CLIENT

If you do not want to use this function, you copy the code in the function outside and use the domino clause to get the last part of the IP address. Like this:

user_210="radek"
user_209="mike"
ip_last_part=`env | grep -i SSH_CLIENT | cut -d ' ' -f1 | cut -d '.' -f4`
eval user=$`echo "user_$ip_last_part"`
echo "User '$user' identified for ip ending in '$ip_last_part'"
alias sites="cd /var/lib/code/$user"
echo "Alias defined : `alias sites`"

NTN,
Madhur Tanwani

+1
source

Source: https://habr.com/ru/post/1758162/


All Articles