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.

    2 Answers 2

    3

    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 
      1

      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.

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

      You must log in to answer this question.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.