Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a one-line file with a value stored as a string in it:

server-name-2009-August-9-AMI

The file name is server_name. What's the shortest, most elegant way to rad this value into a variable with bash script?

share|improve this question
add comment

2 Answers

up vote 8 down vote accepted

You can do a "useful use of cat" ;)

VAR = $(cat $(dirname $0)/server_name)

This will put the content of "server_name" file, located in the same directory as your script, into $VAR. Works regardless of where you run the script.

share|improve this answer
1  
The bash man page actually recommends $(< file) over $(cat file). –  chepner Aug 23 '12 at 2:00
add comment

You can use the read command. If you don't provide any variable, the line gets saved automatically into the variable REPLY in Bash. If you provide a singe variable, the line gets saved into that variable. If you provide multiple variables, Bash will split the line as words (the splitting is done on whitespace), trying to put one word into each variable. (If there are more words than variables, each variable gets one word, but the last gets the rest of the line.)

Example:

telemachus ~ $ read < buff
telemachus ~ $ echo $REPLY
#!/usr/bin/env perl
telemachus ~ $ read LINE < buff
telemachus ~ $ echo $LINE
#!/usr/bin/env perl

Note that the variable is assigned without a dollar sign (REPLY or LINE), but when you use it, you need $REPLY or $LINE.

So you would want something like this:

read SERVER < /path/to/server_name

I recommend that you use the full path of the file that you want to read rather than assuming that the two scripts will be in the same directory.

I won't swear that this is the most elegant solution.

share|improve this answer
1  
+1 for the concise, complete explanation of read. –  Ryan Thompson Sep 8 '09 at 0:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.