blaCkninJa
blaCkninJa

Reputation: 455

Duplicate the output of bash script

Below is the piece of code of my bash script, I want to get duplicate output of that script.

This is how my script runs #bash check_script -a used_memory

Output is: used_memory: 812632

Desired Output: used_memory: 812632 | used_memory: 812632

get_vals() {
     metrics=`command -h $hostname -p $port -a $pass info | grep -w $opt_var | cut -d ':' -f2 > ${filename}`
}

output() {
get_vals
if [ -s ${filename} ];
then
   val1=`cat ${filename}`
   echo "$opt_var: $val1"
   # rm $filename;
    exit $ST_OK;
else
     echo "Parameter not found"
     exit $ST_UK
fi
}

But when i used echo "$opt_var: $val1 | $opt_var: $val1" the output become: | used_memory: 812632

$opt_var is an argument.

Upvotes: 0

Views: 420

Answers (1)

vdavid
vdavid

Reputation: 2544

I had a similar problem when capturing results from cat with Windows-formatted text files. One way to circumvent this issue is to pipe your result to dos2unix, e.g.:

val1=`cat ${filename} | dos2unix`

Also, if you want to duplicate lines, you can use sed:

sed 's/^\(.*\)$/\1 | \1/'

Then pipe it to your echo command:

echo "$opt_var: $val1" | sed 's/^\(.*\)$/\1 | \1/'

The sed expression works like that:

  1. 's/<before>/<after>/' means that you want to substitute <before> with <after>
  2. on the <before> side: ^.*$ is a regular expression meaning you get the entire line, ^\(.*\)$ is basically the same regex but you get the entire line and you capture everything (capturing is performed inside the \(\) expression)
  3. on the <after> side: \1 | \1 means you write the 1st captured expression (\1), then the space character, then the pipe character, then the space character and then the 1st captured expression again

So it captures your entire line and duplicates it with a "|" separator in the middle.

Upvotes: 1

Related Questions