Omar
Omar

Reputation: 91

Read value from file & put it into a variable

I am trying to read file that contains a single line

cpu=msm8998

I need to grab the value after "=" and assign it to a variable. What's the simplest way to do it ? without using cat if possible

Upvotes: 0

Views: 329

Answers (5)

Kingsley
Kingsley

Reputation: 14924

Assuming this text is in a file cpu.txt:

#! /usr/bin/env bash

CPU_FILE="cpu.txt"

CPU=`awk -F= '{ print $2 }' "$CPU_FILE"`
echo "\$CPU = $CPU"

Using awk to split on the = (that's the awk -F=), output the 2nd field ( { print $2 }), then store the output of all that into $CPU with back-tick enclosure (I'm not sure of the proper name for this, if any).

Upvotes: 1

William Pursell
William Pursell

Reputation: 212684

If your input file is just that one line, then you should source it:

$ cat input  

cpu=msm8998
$ echo $cpu 

$ . input
$ echo $cpu
msm8998

Upvotes: 3

Eric Renouf
Eric Renouf

Reputation: 14520

If that's really all that's in the other file, I'd just source it, the example you gave is a valid shell assignment:

$ cat file
pu=msm8998
$ cat using_it
#!/bin/bash

. file
printf '%s\n' "$cpu"

$ ./using_it
msm8998

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158280

Use the read builtin:

IFS== read name value < file
echo "${value}"

read splits the input into fields delimited by IFS the shell's internal field separator. In your example the field separator is =.

Alternatively, just source the file:

source file
echo "${cpu}"

Upvotes: 5

l0b0
l0b0

Reputation: 58998

This will do it:

my_var="$(cut -d= -f2 my_file.txt)"

The cut command basically says to split each line in my_file.txt into fields separated by equals signs, and print only the second field.

Test session:

$ echo cpu=msm8998 > my_file.txt
$ my_var="$(cut -d= -f2 my_file.txt)"
$ echo "$my_var"
msm8998

Upvotes: 1

Related Questions