Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This bash script runs on a Mac terminal, it needs to ask the user for input $name, then replace a string in another file to include the user input PLACEHOLDER_BACKEND_NAME=$name.

#!/bin/bash
read -r name

if ! grep -q PLACEHOLDER_BACKEND_NAME="\"$name\"" ~/path-to-file.sh; then
perl -pi -e 's/PLACEHOLDER_BACKEND_NAME.*/PLACEHOLDER_BACKEND_NAME=$name/g' ~/psth-to-file.sh
fi

The perl replace command fail to take in the value in the $name variable. I am not familiar with Bash.

share|improve this question
up vote 0 down vote accepted

Variables are not expanded within single-quotes. The $name variable is within single-quotes. You can fix that by breaking out of the single-quotes in the middle:

perl -pi -e 's/PLACEHOLDER_BACKEND_NAME.*/PLACEHOLDER_BACKEND_NAME='"$name"'/g' ~/psth-to-file.sh

Notice that I double quoted the variable, to protect from globbing and word splitting.

share|improve this answer
    
Just beware if $name can contain spaces or tabs or newlines... – Jeff Schaller 2 days ago
    
Jeff, as I double quoted the variable, I don't see what you mean – janos 2 days ago
    
You did -- my mistake! – Jeff Schaller 2 days ago

bash doesn't expand the variable content inside a single quote string. You have to use double quoted strings.

Examples :

This will print : my name is : $name

name="haha"
echo 'my name is : $name'

This will print : my name is : haha

name="haha"
echo "my name is : $name"

So just replace

perl -pi -e 's/PLACEHOLDER_BACKEND_NAME.*/PLACEHOLDER_BACKEND_NAME=$name/g' ~/psth-to-file.sh

with

perl -pi -e "s/PLACEHOLDER_BACKEND_NAME.*/PLACEHOLDER_BACKEND_NAME=$name/g" ~/psth-to-file.sh
share|improve this answer

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.