3

i'm new to shell scripting. I'm learning little by little. I'm more familiar with php which is working toward my disadvantage right now.

Anyway, i'm writing a shell script and i read in input with the following:

read $foo

i now want to use this variable in my sed string replacement like so:

sed -i 's/replaceme/$foo' myfile.txt

What i'm getting instead is the literal substitution not what $foo actually equals. Instead i want it to be the input of the user:

Example:

Using this line ( read $foo ) . Say i type 'bar'. Thus $foo='bar' from user input.

Current Output: $foo

Desired Output bar

Hope that makes sense.

  • 1
    1. read foo (no $-sign before foo, otherwise it will expand foo, which is unset most likely); 2. sed "s/regex/$foo/" to actually expand foo inside the sed argument. – alex Jul 11 '11 at 20:11
2

The short answer: Use double quotes instead of single quotes.

Single quotes prevent expanding shell variables, while double quotes do not.

For far more detail see http://www.grymoire.com/Unix/Quote.html

The full details are included in the documentation of your shell, and there is some variation between the different shells, but the basics are the same in nearly every Unix-style shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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