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

180,354

Solution 1

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.

Solution 2

Use the double quotes. Try this

var="$(cat foo.txt)"
Share:
180,354

Related videos on Youtube

eltigre
Author by

eltigre

Updated on September 18, 2022

Comments

  • eltigre
    eltigre almost 2 years

    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?

  • G-Man Says 'Reinstate Monica'
    G-Man Says 'Reinstate Monica' about 7 years
    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.
  • sojim2
    sojim2 over 5 years
    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
  • jvriesem
    jvriesem over 5 years
    @G-Man: What if that variable contains newlines or tabs that we want to stay in the variable?
  • G-Man Says 'Reinstate Monica'
    G-Man Says 'Reinstate Monica' over 5 years
    @jvriesem:  What if it does?   Do you have a question?
  • Kevin McCarpenter
    Kevin McCarpenter about 5 years
    When I run this command, it seems to get rid of all of my newlines.
  • myhouse
    myhouse almost 5 years
    @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
    myhouse almost 5 years
    @sojim Do you know the answer of this?
  • neokyle
    neokyle over 3 years
    @K.Carpenter echo $var would get rid of newlines, but echo "$var" should show the new lines