Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read bash environment variable

Tags:

linux

bash

i have a program which gives out an environement variable

TIME=1328189073
CLIENT[if-modified-since]=Thu, 02 Feb 2012 12:09:40 GMT
HTTP_FILE=/news/rss.xml?edition=uk
HTTP_PORT=80
HTTP_HOST=feeds.bbci.co.uk
HTTP_PROTO=http
CLIENT[host]=feeds.bbci.co.uk
CLIENTID=10
CLIENT[user-agent]=Safari
PWD=/
VERSION=SR.4.2.2.MR.20110523
CLIENT[accept]=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
SHLVL=1
CLIENT[accept-language]=en-gb,en;q=0.5
INTERFACE=192.168.221.196
CLIENT[cache-control]=max-age=0
CLIENT[accept-encoding]=gzip, deflate
HTTP_METHOD=GET
CLIENT[user-agent]

however when i try to access one of this variable from a bash script it gives no result

echo ${CLIENT[user-agent]} >> ${LOG}

however this works

echo ${TIME} ${CLIENTID} ${USERNAME} ${IP} ${HTTP_METHOD} ${HTTP_PROTO} ${HTTP_HOST} ${HTTP_PORT} ${HTTP_FILE} ${SIZE} >> ${LOG}

any idea why the user-agent fails to show?

like image 386
krisdigitx Avatar asked Feb 03 '12 17:02

krisdigitx


2 Answers

You need to source your script instead of running it.

. set-vars-script.sh
like image 139
Kevin Avatar answered Nov 11 '22 22:11

Kevin


You can not use braces in form ${VAR[ARITHM_EXPR]}. But you can always extract value of these variables to variables with VALID names:

  $ set | sed -n '/CLIENT\[user-agent]=/{s|.*=||;p;q;}'

Why you don't use Perl/Python for scripting? This resolve your problem:

  import os
  print(os.environ['CLIENT[user-agent]'])
like image 20
gavenkoa Avatar answered Nov 11 '22 22:11

gavenkoa