Gabor Gabor - 1 year ago 129
Bash Question

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

I'm trying to make this temperature log in Raspberry Pi happen (though some of the code did not work therefore I used slightly diff. solutions):

I'm stuck with writing the results in a file. I want to create a file that's name contains the actual date, e.g. temperature_log_2016_08_13.txt

When running the script I get an ambiguous redirection error each time lines with the echo commands execute. I tried all sort of combinations with quotes, double-quotes, no quotes. Pls advice.


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

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


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

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

UPDATE: by putting the file name between quotation marks, as advised below, the ambiguous redirect error is gone, but instead the script produces 5 files with the date/timestamp in its name. I need only 1 file into which all the temperatures are written.

Answer Source

The $(date) in your example produces a timestamp with blanks. You might either use your function ($(timestamp)) instead, or quote the whole target filename (or both):

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

And it is best to actually evaluate the timestamp in the filename only before the loop, otherwise you get a new file every second or minute:

# %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}
    temp=$(/opt/vc/bin/vcgencmd measure_temp)
    echo "${temp} $(timestamp)" >> "$logfile"
    sleep 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download