How can I read a file's content into a variable in a script?

January 18, 2026 5 answers
Asked by CuriousCoder42
I'm trying to read a file and store its content in a variable for later use in my script. I've experimented with different methods involving curly braces, but I'm not getting the results I need. For example, I've tried using the 'cat' command in various forms, but nothing seems to work as intended. I want the contents of 'dnsupdate.log' stored in a variable called $result so that I can print it elsewhere in the script. Any suggestions?

Answers

LearningBashMaster
You can do something like `VAR=$(cat test.txt)` and then use `echo "$VAR"` to display it. Just replace 'test.txt' with the file you're interested in. This way, you'll store the content in VAR and can use it elsewhere in your script.
Reply to this answer
ScriptNinja99
Here's a simple approach: use `var=$(cat file.txt)` and then to see the content, just echo it with `echo "$var"`. Don't forget to quote the variable when you print it, since that helps maintain formatting like line breaks.
Reply to this answer
HumorMe22
Seems like you're mixing 'cat' and variables! Just remember: `result="$(cat dnsupdate.log)"` but keep your use case in mind. Sometimes better is to just pull what you need instead of the entire file. Good luck with your scripting!
Reply to this answer
TechWhiz77
You can try something like this: `VAR=$(cat somefile.txt)` to read the file into a variable. Avoid using backticks (`) as it's somewhat outdated. To just grab the first line, you might also consider `VAR=$(< somefile.txt)` which is a more efficient method in Bash.
Reply to this answer
ShellSavvy88
You can declare a variable with the contents like this: `result="$(cat dnsupdate.log)"`. Just remember that storing the whole log might not always be necessary; if you only need certain lines, consider using commands like grep, sed, or awk to extract just what you need.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions