Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to a bash variable whose name contains dot

Tags:

bash

I have a bash variable: agent1.ip with 192.168.100.137 as its value. When I refer to it in echo like this:

echo $agent1.ip

the result is:

.ip

How can I access the value?

UPDATE: my variables are:

enter image description here

like image 706
Taher Khorshidi Avatar asked Oct 22 '14 11:10

Taher Khorshidi


People also ask

Can variable name have dot?

A valid variable name consists of letters, numbers and the dot or underline characters.

Can environment variable have dots?

It is not possible to set environment variables with dots in their name. If you try to set one in the UI, it just does not work without error message.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What symbol is used to reference a variable that has been defined in bash?

You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.


2 Answers

Bash itself doesn't understand variable names with dots in them, but that doesn't mean you can't have such a variable in your environment. Here's an example of how to set it and get it all in one:

env 'agent1.ip=192.168.100.137' bash -c 'env | grep ^agent1\\.ip= | cut -d= -f2-'
like image 108
John Zwinck Avatar answered Sep 19 '22 15:09

John Zwinck


Since bash.ip is not a valid identifier in bash, the environment string bash.ip=192.168.100.37 is not used to create a shell variable on shell startup.

I would use awk, a standard tool, to extract the value from the environment.

bash_ip=$(awk 'BEGIN {print ENVIRON["bash.ip"]}')
like image 26
chepner Avatar answered Sep 20 '22 15:09

chepner