简体   繁体   中英

bash 'ls' can't find the file after checking that file exists

I have this simple code

#!/bin/bash

TIMEOUT=60

# call a function that creates a file
LOG_FILE_NAME="/dir/something.txt"
create_a_file(LOG_FILE_NAME)

until [ ! -f ${LOG_FILE_NAME} ] || [ "$TIMEOUT" == "0" ]
do
    echo "Slept 1 second while waiting for file creation"
    sleep 1
    ((TIMEOUT--))
done

for file in $(ls -tr /dir/*.txt); do
    #something
done

Most times this works but sometimes I get: ls: cannot access /dir/*.txt: No such file or directory

ls: cannot access /dir/*.txt: No such file or directory

It means there are no *.txt files in /dir/ . (When the glob doesn't match anything the shell passes the literal asterisk to ls , as if you had written ls '/dir/*.txt' .)

The problem is the loop condition. It shouldn't have ! .

until [ -f ${LOG_FILE_NAME} ] || [ "$TIMEOUT" == "0" ]

(If the timeout hits 0 you'll still see the same error, though.)

It's better to use [[ , by the way, to avoid quoting issues.

until [[ -f $LOG_FILE_NAME || $TIMEOUT == 0 ]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM