我正在 crontab 中执行以下命令:
nice --20 iperf3 -c somelocation.com -f k | while IFS= read -r line; do echo "$(date) $line"; done | tee onespeed.txt | tee -a speeds.txt; sleep 30 ;cat onespeed.txt | grep sender >> concentrated.txt; sleep 2 ;cat onespeed.txt | grep sender | awk -F' ' '{print $13}' | while IFS= read -r line; do echo "$(date) $line"; done | tee onerawspeed.txt | tee -a rawspeeds.txt
我知道这项工作可以用更优雅的方式完成,但我想知道如何分解它,以便它的结构正确地充当 bash shell 脚本。
特别是我专注于在多行上构建它,以便它更具可读性。
最佳答案
将代码包装在任意函数中 n() { one-liner_code_here ; }
,然后运行 type n
。 bash
会充实它的很多内容——特别有用的是它如何缩进循环。但是 type
不会打断管道,并且会留下分号,所以这里有一些代码可以使整个业务自动化...
假设一行是一个文件src。下面将 src 放入 $x
,然后为它创建一个函数 n,(这需要一个 eval
对于函数中带引号的字符串应该是无害的),然后 type
将其提供给 sed
忽略周围的括号,分解较长的管道并删除前导缩进和尾随 ;
,然后 unset
n:
read x <src; eval n\(\) \{ "$x" \;\}
type n | sed -n '/^ /{s/^ //;/^[^ ]/s/| /|\n/g;s/\;$//;p}' ; unset -f n
输出:
nice --20 iperf3 -c somelocation.com -f k |
while IFS= read -r line; do
echo "$(date) $line"
done |
tee onespeed.txt |
tee -a speeds.txt
sleep 30
cat onespeed.txt |
grep sender >> concentrated.txt
sleep 2
cat onespeed.txt |
grep sender |
awk -F' ' '{print $13}' |
while IFS= read -r line; do
echo "$(date) $line"
done |
tee onerawspeed.txt |
tee -a rawspeeds.txt
注意:type
也会将当前环境中的任何alias
转换为代码。因此,如果 grep
被 别名
为 grep --color=auto
,则上面的每个 grep
都将被替换为 grep --color=auto
。
关于linux - 将长单行命令转换为 bash shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46339026/