TheOgHotchPotch
TheOgHotchPotch

Reputation: 1

How can I create a linux command that gets the value of a variable from a text file?

I have a file that looks like this:

serverPass i_am_a_password

I am basically looking for a command so I can set an environment variable to i_am_a_password.

I've tried using grep with serverPass but I am not sure how to split the output and somehow pipe it to a environment variable assignment.

Any help is appreciated.

Upvotes: 0

Views: 212

Answers (4)

Ed Morton
Ed Morton

Reputation: 203393

Given that 1-line input file you show, all you need to do is read the line:

read -r _ var < file

Look:

$ cat file
serverPass i_am_a_password

$ read -r _ var < file

$ echo "$var"
i_am_a_password

Upvotes: 0

ufopilot
ufopilot

Reputation: 3975

# if file.txt contains only password line
serverPass=$(awk '{print $2}' file.txt)
echo $serverPass
i_am_a_password

# otherwise use pattern
serverPass=$(awk '/^serverPass / {print $2}' file.txt) 
echo $serverPass
i_am_a_password

# or source all variables from file.txt after changing blank to "="
source <(cat file.txt | tr ' ' '=')
echo $serverPass
i_am_a_password

Upvotes: 1

sseLtaH
sseLtaH

Reputation: 11217

If sed is an option, you can try

$ var=$(sed 's/[^ ]* \(.*\)/\1/' input_file)
$ echo "$var"
i_am_a_password

Upvotes: 1

Mikael Kj&#230;r
Mikael Kj&#230;r

Reputation: 700

This should do it:

PASSWORD=$(cut -d' ' -f2 password.txt)

Now you will have the password in the environment variable called PASSWORD.
Test it with echo $PASSWORD

-d is the delimiter and -f2 means the field to output.

Upvotes: 1

Related Questions