5

I have written a bash script to calculate the size of a PostgreSQL database and print the output along with the date when the script was executed in a text file. The script code is as follows:

#!/bin/bash
date +"%d:%m" >> dbdata.growth
psql -h 192.168.2.173 -U postgres -c "select pg_database_size('ddb'); "  | sed -n    
'3,3p' | numfmt --to=iec >>dbdata.growth
psql -h 192.168.2.173 -U postgres -c "select pg_database_size('dpkidb'); "  | sed  
-n '3,3p' | numfmt --to=iec >>dbdata.growth

The script produces the following output in the format as shown below

26:03
         134G
         4.4M
26:03
         134G
         4.4M

The issue for me is that I want all the three columns in the same row. How can I achieve that?

4

Replace all output lines, such as:

date +"%d:%m" >> dbdata.growth

with lines such as:

date +"%d:%m" | tr -d $'\n' >> dbdata.growth

This uses tr to delete newline characters before they are put in the output file.

tr is a translate or delete utility. In this case, the use of the -d option tells it to delete. The character that we ask it to delete is the newline character, expressed as $'\n'.

  • 1
    Do you really need the $? – Bernhard Mar 26 '14 at 8:16
2

The solution would be to use subshells:

#!/bin/bash
var1=$(date +"%d:%m")
var2=$(psql -h 192.168.2.173 -U postgres -c "select pg_database_size('ddb'); "  | sed -n '3,3p' | numfmt --to=iec)
var3=$(psql -h 192.168.2.173 -U postgres -c "select pg_database_size('dpkidb'); "  | sed  -n '3,3p' | numfmt --to=iec )
echo $var1 $var2 $var3 >>dbdata.growth
0

If you know there are three columns, you could use paste:

your_script.sh | paste - - -
0
#!/bin/bash
{ date +"%d:%m" >> dbdata.growth
psql -h 192.168.2.173 -U postgres -c "select pg_database_size('ddb'); "  | sed -n    
'3,3p' | numfmt --to=iec >>dbdata.growth
psql -h 192.168.2.173 -U postgres -c "select pg_database_size('dpkidb'); "  | sed  
-n '3,3p' | numfmt --to=iec >>dbdata.growth

} | ( 

#all output from your commands above piped to collector subshell below

set -f ; unset IFS ; set -- $(cat)
while [ $# -ge 3 ] ; do {
    printf '%s\t%s\t%s\n' "$1" "$2" "$3"
    shift 3 ; } ; done  
printf '%s\t' "$@"
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.