bash - 使用 Bash 重定向从 UNIX 程序收集数据

标签 bash unix csv

我正在尝试编写一个脚本,根据 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/

相关文章:

bash - 如何判断字符串是否未在 Bash shell 脚本中定义

python - 从 nohup 开始时如何将参数传递给 python 脚本

linux - 保护包含空格的参数免受 eval 的影响

c - 使用套接字通过C中的SOCKS5代理服务器发送请求

python - 如何将 csv 中的每一列保存到列表中?

linux - 期望 "do"的 shell 脚本错误

regex - 从两行之间的文件中提取一个 block

linux - WebDav 检测文件夹的写权限

csv - 向csv文件问题中的每一列添加双引号的脚本

python - 获取 Pandas read_csv() 读入的 dtypes 字典