将多个命令合并到一个 shell 脚本中

将多个命令合并到一个 shell 脚本中

只有当我一一运行命令时,我才能得到所需的输出。如何将所有命令组合在 shell 脚本中并获得所需的输出?

//insert timestamp column
$ vmstat -n 5 | (while read; do echo "$(date +%Y-%m-%d.%H:%M:%S) $REPLY"; done)> vm.txt 
//remove 1st & 2nd row
$ sed '1,2d' vm.txt > vm2.txt 
//convert text file to csv
$ sed 's/^  *//;s/  */,/g'  vm2.txt > vm2.csv 
//insert column name
$ echo $'datetime, r, b, swpd, free, buff, cache, si, so, bi, bo, in, cs, us, sy, id, wa, st' | cat - vm2.csv> chart.csv
$ psql -p 5432 -U postgres -c  "\copy vmstat FROM '/root/report/chart.csv' delimiter '|' csv header"

答案1

以下脚本将执行与您的命令所做的等效操作,但不会创建如此多的中间文件:

#!/bin/sh

report=/root/report/chart.csv

vmstat -n 5 100 |
awk -vOFS=',' 'NR == 1 { next }
               NR == 2 { $1 = "datetime" OFS $1 }
               NR  > 2 { $1 = strftime("%F.%T", systime()) OFS $1 } 1' >"$report"

psql -p 5432 -U postgres -c "COPY vmstat FROM '$report' DELIMITER ',' CSV HEADER"

这使用单个awk脚本在开头插入日期戳列并将输出转换为逗号分隔的记录。它重用了输出的标头,并以 5 秒的间隔vmstat收集 100 行输出。vmstat我还将 PostrgeSQL 语句中使用的分隔符更改为逗号,因为这就是数据所使用的分隔符。

该脚本期望它是大多数 Linux 系统上的awkGNU 。awk

答案2

将所有命令放入一个文件中,假设为 myCommands。请注意#!/bin/sh第一行的 。这称为 shebang,它告诉 shell 在执行时用什么程序解释脚本。

#!/bin/sh
# insert timestamp column
vmstat -n 5 | (while read; do echo "$(date +%Y-%m-%d.%H:%M:%S) $REPLY"; done)> vm.txt 
# remove 1st & 2nd row
sed '1,2d' vm.txt > vm2.txt 
# convert text file to csv
sed 's/^  *//;s/  */,/g'  vm2.txt > vm2.csv 
# insert column name
echo $'datetime, r, b, swpd, free, buff, cache, si, so, bi, bo, in, cs, us, sy, id, wa, st' | cat - vm2.csv> chart.csv
psql -p 5432 -U postgres -c  "\copy vmstat FROM '/root/report/chart.csv' delimiter '|' csv header"

接下来,使其可执行:

chmod +x myCommands

./myCommands现在,如果您位于同一文件夹中,则可以使用它,或者myCommands如果脚本文件位于变量中包含的较旧版本中,则可以使用它$PATH

相关内容