8

how can I read a text file and save it to a variable in bash ? my code is here :

#!/bin/bash
TEXT="dummy"
echo "Please, enter your project name"
read PROJECT_NAME  
mkdir $PROJECT_NAME  
cp -r -f /home/reza/Templates/Template\ Project/* $PROJECT_NAME  
cd $PROJECT_NAME/Latest  
TEXT = `cat configure.ac `  ## problem is here   !!!  
CHANGED_TEXT=${TEXT//ProjectName/$PROJECT_NAME}
echo $CHANGED_TEXT
GreenMatt
  • 18,244
  • 7
  • 53
  • 79
reza
  • 365
  • 2
  • 3
  • 15

3 Answers3

17

The issue is that you have an extra space. Assignment requires zero spaces between the = operator. However, with bash you can use:

TEXT=$(<configure.ac)

You'll also want to make sure you quote your variables to preserve newlines

CHANGED_TEXT="${TEXT//ProjectName/$PROJECT_NAME}"
echo "$CHANGED_TEXT"
SiegeX
  • 135,741
  • 24
  • 144
  • 154
  • it worked but it has a problem :the lines are missing .all the characters become in just 1 line like [this](http://paste.kde.org/200162/) what I should do ? – reza Feb 05 '12 at 02:42
  • 1
    @reza did you quote your variables like I mentioned? – SiegeX Feb 05 '12 at 03:16
5

Try

TEXT=`cat configure.ac`

That should work.

Edit:

To clarify, the difference is in the spacing: putting a space after TEXT causes bash to try to look it up as a command.

Gabriel Grant
  • 5,415
  • 2
  • 32
  • 40
2

For execute a command and return the result in bash script for save in a variable, for example, you must write the command inner to var=$(command). And you mustn't give spaces between var,'=' and $(). Look at this

TEXT=$('cat configure.ac')

Now, echo $TEXT return the content by file configure.ac.

Chemaclass
  • 1,933
  • 19
  • 24