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
1

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

2 Comments

it worked but it has a problem :the lines are missing .all the characters become in just 1 line like this what I should do ?
@reza did you quote your variables like I mentioned?
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.