Bash中nohup运行时是否无法使用变量?


写了一行脚本用来取Linux server上的几个网络数据,并用awk打上timestamp记录:


 for ((i=0;i<5;i++)); do cat /sys/class/net/eth0/statistics/rx_bytes /sys/class/net/eth0/statistics/rx_packets | paste -d' ' - - | gawk '{print systime(), $0}'; sleep 2; done

输出:
1398132841 131363249 780043
1398132843 131367139 780066
1398132845 131371063 780095
1398132847 131375807 780120
1398132849 131381147 780164

但是当我用nohup来执行这条命令时好像就无法正常工作了:


 sh -c "for ((i=0;i<5;i++)); do cat /sys/class/net/eth0/statistics/rx_bytes /sys/class/net/eth0/statistics/rx_packets | paste -d' ' - - | gawk '{print systime(), $0}'; sleep 2; done" > /tmp/net_stat.log &

输出:
1398132882 0
1398132884 0
1398132886 0
1398132888 0
1398132890 0

是不是$0这个变量在nohup运行环境中无法使用的原因?有没有什么解决办法?谢谢!

Linux bash

凯尔萨斯.修 10 years, 7 months ago

nohup 在哪里?

你看代码高亮,其中的 $0 在最外层的 "" 已经被展开了,也就是,gawk 得到的是诸如 {print systime(), -bash} 这样的字符串(具体是什么与你的 shell 及启动方式有关)。你转义一下写成 \$0

vibobb answered 10 years, 7 months ago

Your Answer