Search code examples
bashechoeval

eval to interpret new lines in bash


I have a previously run command $cmd, this command outputs multiple lines.

I would like to take the nth line of output from running an edited version of $cmd.

So far I have tried:

local -a lines

for line in $(eval "$(some_edit $cmd)");do
  lines+=("$line")
done

echo "${lines[$nth_line]}"

I always echo everything when $nth_line is 1 and nothing for larger integers.

I always have $lines being an array of one string - which is all the lines.

I have tried combinations of ", but to no avail.


Solution

  • I don't know if i understand you correct - you mean something like that?

    #!/bin/bash
    cmd="./script.sh"
    
    # read stdout from $cmd into array lines
    readarray lines < <($cmd)
    
    # edit the second line
    lines[1]=$'version: 0.99\n'
    
    # loop over array and print lines
    for line in "${lines[@]}"; do
       printf "%s" "$line"
    done
    

    testscript for simulate $cmd

    #!/bin/bash
    echo "start"
    echo
    echo "do something"
    echo
    echo "end"
    

    output

    start
    version: 0.99
    do something
    
    end