Search code examples
linuxbashshellawksh

print command output stored in bash variabled as it with wothout removing new line


i just want to write a bash program that stores top 5 process on variable as it is without removing new lines.

#!/bin/bash
getTopProcess(){
    top_output=$(top -n 1 -b -o %CPU | awk 'NR>=8 && NR <=12')
    echo $top_output
}

getTopProcess

but my code print all in same line, can anyone help me with this

output i get:

1937738 kavin-1+ 20 0 36.6g 153432 112596 S 6.2 1.0 0:22.70 code 1996549 root 20 0 23364 6208 4768 R 6.2 0.0 0:00.01 top 1 root 20 0 168216 10188 5496 S 0.0 0.1 1:28.14 systemd 2 root 20 0 0 0 0 S 0.0 0.0 0:00.62 kthreadd 3 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 rcu_gp

output i want:

   1845 root      20   0 1407168   1372   1372 S   6.2   0.0   0:48.68 lwsmd
1851644 kavin-1+  20   0 1131.0g  88896  61588 S   6.2   0.6   0:48.23 ulaa
      1 root      20   0  168216  10188   5496 S   0.0   0.1   1:28.14 systemd
      2 root      20   0       0      0      0 S   0.0   0.0   0:00.62 kthreadd
      3 root       0 -20       0      0      0 I   0.0   0.0   0:00.00 rcu_gp

Solution

  • you need to double-quote the variable when you echo it, because by adding the double quotes around "$top_output", the variable will be expanded with the newlines intact!

    #!/bin/bash
    getTopProcess(){
        top_output=$(top -n 1 -b -o %CPU | awk 'NR>=8 && NR <=12')
        echo "$top_output"
    }
    
    getTopProcess
    

    output

      99476 root      20   0   16448  10084   8236 S  12.5   0.5   0:00.05 sshd
        559 root      20   0   80056   1512   1316 S   6.2   0.1  12:01.06 qemu-ga
        636 mysql     20   0 1361792 417352  19292 S   6.2  21.3 101:01.98 mysqld
      99480 root      20   0   10344   4088   3488 R   6.2   0.2   0:00.02 top
          1 root      20   0  167600  13096   8416 S   0.0   0.7   2:35.51 systemd
    

    You can also use the readarray command, because it is used to read the output of the top command into the top_output array.

    #!/bin/bash
    getTopProcess(){
        readarray -t top_output < <(top -n 1 -b -o %CPU | awk 'NR>=8 && NR <=12')
        for line in "${top_output[@]}"; do
            echo "$line"
        done
    }
    
    getTopProcess