Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string/array operations in bash?

Tags:

linux

bash

I want to so something like that in bash (.bashrc) so the alias is set based on which comp the user logged in. I don't know how to get the 210 from 10.0.0.210 and then the best way of going through of the list 'user=xxx'

$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 likeg

'cd /var/lib/code/radek' if logged from 210 computer

'cd /var/lib/code/mike' if logged from 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]##*.}]}
like image 373
Radek Avatar asked Apr 28 '26 02:04

Radek


1 Answers

Give this a 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
like image 183
Dennis Williamson Avatar answered Apr 30 '26 14:04

Dennis Williamson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!