SorveO
SorveO

Reputation: 3

No such file or directory in Bash?

My bash script. After its completion, it receives line 9: 1570066642: No such file or directory

#!/bin/bash

DATE=$(date "+%s")

while read p; do

IFS=',' read -ra my_array <<< "$p"

if [ "${my_array[1]}" < "${DATE}" ] ; then
    continue
fi

echo "$p" >> my_file.txt

done <cache_data.txt

mv my_file.txt cache_data.txt

I want to check the difference between dates in timestamp seconds.

Upvotes: 0

Views: 1478

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

Use (( for arithmetic operations.

if ((${my_array[1]} < DATE)); then

If you do use [ then you need to change < to -lt. Unlike ((, [ is not special shell syntax. It is just a regular command with an unusual single character name, which means that the shell interprets < as a file redirection rather than a less than operator.

if [ "${my_array[1]}" -lt "${DATE}" ] ; then

You can simplify the read calls. Instead of reading a whole line and then calling read a second time to parse the comma-separated fields you can do both at once.

You also don't need to read the results into an array. read can assign to multiple variables at once.

Finally, if you hoist the >> my_file.txt redirection out of the loop you can avoid opening and closing the file every iteration, a nice optimization.

while IFS=',' read -r field1 timestamp rest_of_line; do
    ((timestamp >= DATE)) || continue
    echo "$field1 $timestamp"
done <cache_data.txt >my_file.txt

I like to use && and || as shorthand for if and if !. They're a common shell scripting idiom for quick tests. I've used || above to demonstrate. You may find that more or less readable. Opinions vary.

Upvotes: 2

Related Questions