27

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?

34
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.

  • 3
    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 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 at 16:53
  • @sojim Do you know the answer of this? – myhouse Jul 13 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 at 15:01
3

Use the double quotes. Try this

var="$(cat foo.txt)"
  • 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 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 at 22:29
  • @jvriesem:  What if it does?   Do you have a question? – G-Man Mar 8 at 4:49
  • When I run this command, it seems to get rid of all of my newlines. – K. Carpenter Apr 18 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.