使用日期创建文件名时 shell 脚本中出现不明确的重定向错误

Ambiguous redirect error in shell scripting when creating file name with date

我正在尝试让这个温度登录 Raspberry Pi 发生(虽然有些代码不起作用因此我使用了稍微不同的解决方案):

https://www.raspberrypi.org/learning/temperature-log/worksheet/

我坚持将结果写入文件。我想创建一个名称包含实际日期的文件,例如temperature_log_2016_08_13.txt

当 运行 脚本出现 不明确的重定向错误时 每次执行回显命令时。我尝试了各种带引号、双引号、不带引号的组合。请指教。

#!/bin/bash

timestamp() {
    date +%F_%H-%M-%S
}

temperature() {
    /opt/vc/bin/vcgencmd measure_temp
}

temp=$(temperature)
temp2=${temp:5:9}

echo Temperature Log_$(date) >/home/pi/logs/temperature_log_$(date).txt

for i in {1..5}
do
    echo ${temp2} $(timestamp) >>/home/pi/logs/temperature_log_$(date).txt
    sleep 1
done

更新:通过将文件名放在引号之间,如下所示,不明确的重定向错误消失了,但脚本生成了 5 个名称中包含 date/timestamp 的文件。我只需要 1 个文件,其中写入了所有温度。

您的示例中的 $(date) 会生成带空格的时间戳。您可以改用您的函数 ($(timestamp)),或引用整个目标文件名(或两者):

echo bla >> "/home/pi/logs/temperature_log_$(timestamp).txt"

并且最好只在循环之前实际评估文件名中的时间戳,否则你每秒或每分钟都会得到一个新文件:

# %F: full date; same as %Y-%m-%d
logfile = "/home/pi/logs/temperature_log_$(date +%F).txt" 
echo "Temperature Log_$(date)" > "$logfile" # overwrite if started 2 times a day
for i in {1..5}
do
    temp=$(/opt/vc/bin/vcgencmd measure_temp)
    temp=${temp:5:9}
    echo "${temp} $(timestamp)" >> "$logfile"
    sleep 1
done

date 的输出包含空格。您需要用双引号将文件名作为空格的一部分:

echo Temperature Log_$(date) > "/home/pi/logs/temperature_log_$(date).txt"

或者使用你的函数,但是无论如何引用文件名是一个好习惯。