0

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.

0

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.

  • Just beware if $name can contain spaces or tabs or newlines... – Jeff Schaller Dec 26 '16 at 15:25
  • Jeff, as I double quoted the variable, I don't see what you mean – janos Dec 26 '16 at 15:30
  • You did -- my mistake! – Jeff Schaller Dec 26 '16 at 15:32
1

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

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.