我正在尝试编写一个脚本,该脚本根据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"
答案 0 :(得分:1)
这是一个重写错误和习语违规的修复。
#!/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
“正确”进行简单处理更复杂。
答案 1 :(得分:0)
试试这个。
#!/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"
read -p 'Enter the time interval for collecting data in seconds: ' t
if hash acpi 2>/dev/null; then
echo -e "time,temperature\n" > "$output_csv"
while (true); do
sleep $t
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 [ -n "$1" ]; then
local output_csv = $1
start_log
else
echo -e "Error: No filename specified.\n"
fi
echo -e "\n"