Home > Enterprise >  How to use text file variables in bash script
How to use text file variables in bash script

Time:09-06

I have a variable text file, in which All of my variables are there. I wrote a script through which I get the content of the file, here's the script:

#!/bin/sh
value=`cat dev.txt`
echo "$value"

And I got this output on my terminal screen.

location = "centralus"
location_abr = "cus"
client_name = "fair"
client_name_prefix = "f"
resource_group_postfix = "rg"
project_name = "OTOZ"
environment_name = "devtest"
instance = "04"
Clusterabr= "aks"

But, I want to use the value of the variables which I got in the output. For example, I want to get the value of Clusterabr, But I cannot get it.

CodePudding user response:

Would you please try the following:

#!/bin/bash

declare -A ary                  # associative array to store name-value pairs
pat='^([^[:space:]] )[[:space:]]*=[[:space:]]*"([^"] )"$'
while IFS= read -r line; do
    if [[ $line =~ $pat ]]; then
        ary[${BASH_REMATCH[1]}]="${BASH_REMATCH[2]}"
    fi
done < dev.txt

echo "${ary[Clusterabr]}"       # example

Output:

aks
  • The regex $pat matches the line assiging ${BASH_REMATCH[1]} to the lvalue and ${BASH_REMATCH[2]} to the rvalue.
  • ary[$name]="$value" assigns an associative array ary indexed by "$name" to "$value".

CodePudding user response:

value=`cat dev.txt`
# echo "$value"
#get the value of Clusterabr in dev.txt
value1=`cat dev.txt | grep Clusterabr | cut -d "=" -f2`
echo $value1
#remove "" from the value
value2=`echo $value1 | sed 's/"//g'`
echo $value2

The result:

enter image description here

CodePudding user response:

I have an even better solution, based on the source command, as you can see:

Prompt>source dev.txt
Prompt>echo $location
Prompt>centralus

I must admit that you might need to do a small modification in your code, removing the spaces around the = characters, like:

Prompt>cat dev.txt
location="centralus"
location_abr="cus"
...

As you might have guessed, the source command treats your dev.txt file as a piece of script source code.

  • Related