我正在尝试编写一个脚本,根据 acpi 程序给出的温度值输出 CSV 文件(由用户指定)。每个数据条目每秒都会附加到 CSV 文件中(目前)。
我的脚本中有两个问题需要解决:
修复脚本中的错误(例如第14行的文件访问错误),并允许用户指定时间延迟。
这是 bash 脚本:
#!/bin/bash
# This script monitors the CPU temperature (in degrees C) over time, and
# records the data to a CSV file.
# Written by Ben Cottrell
function start_log()
{
touch "$output_csv"
if hash acpi 2>/dev/null; then
echo -e "time,temperature\n" > "$output_csv"
while (true); do
sleep 1
echo -e "$(date +%T),$(acpi -t | awk '{print $4}')\n" >> "$output_csv"
done
else
echo "Error: acpi is not installed. Please execute \"sudo apt-get install acpi, before running this script.\""
fi
}
if [ "$1" ]; then
local output_csv = $1
start_log
else
echo -e "Error: No filename specified.\n"
fi
echo -e "\n"
最佳答案
这是一个重写,修复了最严重的错误和习语违规。
#!/bin/bash
function start_log()
{
local output_csv=$1
local delay=$2
if hash acpi 2>/dev/null; then
echo "time,temperature" > "$output_csv"
while true; do
sleep "$delay"
echo "$(date +%T),$(acpi -t | awk '{print $4}')"
done >>"$output_csv"
else
cat <<________error >&2
$0: Error: acpi is not installed.
Please execute \"sudo apt-get install acpi\" before running this script.
________error
exit 2
fi
}
delay=1 # default to 1 sec delay
while true; do
case $1 in
-t) shift; delay=$1; shift;; # Maybe validate the value of $delay
-*) echo "$0: Unknown option: '$1'" >&2; exit 1;;
*) break;;
esac
done
if [ "$1" ]; then
start_log "$1" "$delay"
else
echo "$0: Error: No filename specified." >&2
exit 1
fi
当从另一个脚本调用它时,在错误消息中包含程序名称很有用,该脚本可能会从另一个脚本等调用。
注意重定向是如何在循环之后只进行一次的,而不是在主循环中重复进行。
另请注意该函数如何从调用者处接收其参数,而不是引入全局变量。
手工制作选项解析并不比使用getopts
“正确”进行简单处理更复杂。
关于bash - 使用 Bash 重定向从 UNIX 程序收集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926550/