Pectus Excavatum
Pectus Excavatum

Reputation: 3783

How to parse a file with one line in shell

This is probably a silly question, but what is the best way to get the string from a text file which has only one line using shell. I know I can use while read, but seems like it might be unecessary.

The file I am reading contains a string directory path, and all I want to do is set that string value to a variable.

if [ -e ${DIR}/test.txt ] ; then
    # set the string within the file to a variable
fi

Upvotes: 0

Views: 229

Answers (3)

tinkertime
tinkertime

Reputation: 3042

How about just using unix cat

var=$(cat ${DIR}/test.txt)

Upvotes: 2

suspectus
suspectus

Reputation: 17268

read is absolutely fine:

read var < test.txt

Upvotes: 2

William Pursell
William Pursell

Reputation: 212288

My personal preference is:

DIR=$( cat file )

but

read DIR < file

works nicely as well

Upvotes: 4

Related Questions