sed and environment variables in bash – backquote!

by krisrowland

I’ve been trying to set the contents of a text file as the value of an environment variable in my bash. I found out that sed can stream the text from a file with something like:

sed -n 123p filname

Here “123” is the line number of the text file you want to pull the text from from and “filname” is the name of the file (extension included).

However, when I tried to set the output to an environment variable as:

myvar=’sed -n 123p filename’

the variable actually takes the value of the contents in the quotes. i.e. a string. I wanted the output of the command as the variable contents, not the command itself.

To set the output of a command as the value of the variable, use backquotes: `. e.g:

myvar=`sed -n 123p filename`

This syntax first executes the contents of the string and then uses the result as indicated (setting the output to a variable in this case). SWEET!

Advertisements