linux - 将长单行命令转换为 bash shell 脚本

标签 linux bash shell awk

我正在 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 nbash 会充实它的很多内容——特别有用的是它如何缩进循环。但是 type 不会打断管道,并且会留下分号,所以这里有一些代码可以使整个业务自动化...

假设一行是一个文件src。下面将 src 放入 $x,然后为它创建一个函数 n,(这需要一个 eval对于函数中带引号的字符串应该是无害的),然后 type 将其提供给 sed 忽略周围的括号,分解较长的管道并删除前导缩进和尾随 ;,然后 unsetn:

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/

相关文章:

bash - 这个脚本有什么作用?

database - 使用 COPY FROM stdin 加载表,只读取输入文件一次

arrays - ubuntu上shell中的数组问题

bash - 从网页源获取链接的绝对路径

Python测试客户端是否存在

linux - 将DOS程序移植到linux上通过usb读写串口

c++ - 我可以获得在键盘上按下某个键的时间量吗

linux - 检查 git 提交是否是一天的第一天的脚本

regex - 尝试设置Guardfile用于web开发,无法添加子目录检查

php - 简单的选择返回意想不到的结果