How to assign the cat output of a bash script to a variable in another script

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

    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

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

    @sojim Do you know the answer of this?

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

  • Use the double quotes. Try this

    var="$(cat foo.txt)"

    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: What if that variable contains newlines or tabs that we want to stay in the variable?

    @jvriesem:  What if it does?   Do you have a question?

    When I run this command, it seems to get rid of all of my newlines.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM