Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to assign the contents of a text file to a variable in a bash script

Tags:

bash

I am very new to making bash scripts, but my goal here is to take a .txt file I have and assign the string of words in the txt file to a variable. I have tried this (no clue if I am on the right track or not).

#!/bin/bash
FILE="answer.txt"
file1="cat answer.txt"
print $file1

When I run this, I get

Warning: unknown mime-type for "cat" -- using "application/octet-stream"
Error: no such file "cat"
Error: no "print" mailcap rules found for type "text/plain"

What can I do to make this work?

Edit** When I change it to:

#!/bin/bash
    FILE="answer.txt"
    file1=$(cat answer.txt)
    print $file1

I get this instead:

Warning: unknown mime-type for "This" -- using "application/octet-stream"
Warning: unknown mime-type for "text" -- using "application/octet-stream"
Warning: unknown mime-type for "string" -- using "application/octet-stream"
Warning: unknown mime-type for "should" -- using "application/octet-stream"
Warning: unknown mime-type for "be" -- using "application/octet-stream"
Warning: unknown mime-type for "a" -- using "application/octet-stream"
Warning: unknown mime-type for "varible." -- using "application/octet-stream"
Error: no such file "This"
Error: no such file "text"
Error: no such file "string"
Error: no such file "should"
Error: no such file "be"
Error: no such file "a"
Error: no such file "varible."

When I enter cat answer.txt it prints out this text string should be a varible like it should but, I still can't get the bash to do that with the varible.

like image 294
BluGeni Avatar asked Jan 02 '13 04:01

BluGeni


People also ask

Can you assign variables in Bash?

A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.


3 Answers

You need the backticks to capture output from a command (and you probably want echo instead of print):

file1=`cat answer.txt`
echo $file1
like image 181
Jeffrey Theobald Avatar answered Oct 11 '22 16:10

Jeffrey Theobald


In bash, $ (< answer.txt) is equivalent to $ (cat answer.txt), but built in and thus faster and safer. See the bash manual.

I suspect you're running this print:

NAME  
    run-mailcap, see, edit, compose, print − execute programs via entries in the mailcap file
like image 84
glenn jackman Avatar answered Oct 11 '22 15:10

glenn jackman


The $() construction returns the stdout from a command.

file_contents=$(cat answer.txt)
like image 42
harpo Avatar answered Oct 11 '22 16:10

harpo