I have a bash script that produces a cat output when it takes an argument. I also have another bash script that executes the first bash script with an an argument that I want to produce cat outputs with. How do I store those cat outputs produced by the first bash script in variables?

var=$( cat foo.txt )

would store the output of the cat in variable var.

var=$( ./myscript )

would store the output of myscript in the same variable.

| improve this answer | |
  • 5
    quick tip for bash newbies like me, the spacing & non spacing are all important, follow exact pattern! for example var = $( cat foo.txt ) will not work – sojim2 Feb 17 '19 at 22:12
  • @Dalker is there a limit how big the foo.txt can be? I have over 10 mb of data. Would cat store the whole thing? I want to know if there's a limit also for future reference. – myhouse Jul 13 '19 at 16:53
  • @sojim Do you know the answer of this? – myhouse Jul 13 '19 at 16:53
  • 1
    @myhouse According to this answer there is no limit due to bash itself, but the limit is rather the memory allocated on the underlying environment, which may of course vary. – Dalker Jul 18 '19 at 15:01

Use the double quotes. Try this

var="$(cat foo.txt)"
| improve this answer | |
  • 3
    It's almost never a bad idea to put things (especially things that begin with $) into double quotes, and it doesn't hurt here. However, in the case of assignment to a variable, it doesn't actually help. – G-Man Says 'Reinstate Monica' May 24 '17 at 4:59
  • @G-Man: What if that variable contains newlines or tabs that we want to stay in the variable? – jvriesem Mar 7 '19 at 22:29
  • @jvriesem:  What if it does?   Do you have a question? – G-Man Says 'Reinstate Monica' Mar 8 '19 at 4:49
  • 2
    When I run this command, it seems to get rid of all of my newlines. – K. Carpenter Apr 18 '19 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.