Shell script check if file exists?

30,303

You could use a nice bash conditional execution to see whether the file exists or not...

[ -f tmp1.txt ] && echo "Found" || echo "Not found"

Alternatively you could use the find command with the -newer flag...

find /some/dir -type f -newer $startdate -not -newer $enddate
Share:
30,303

Related videos on Youtube

tamani
Author by

tamani

Updated on September 18, 2022

Comments

  • tamani
    tamani almost 2 years

    I wrote a simple backup script which back ups my stuff on a remote server, everything is working great but I'd like to have some sort of report like "backup successful or not".

    this is my script

    # backup CHECK
    date1=`date +"%d.%m.%y - %H.%M"`
    host=`hostname`
    twdate=`date +"%d.%m"`
    performtw=`ls -la|grep "tw"|grep "$twdate" > tmp1.txt`
    echo $performtw
    if
    cat tmp1.txt|grep "tw"
    then
    echo backup successfull
    printf "tw backup success!" | mail -s "tw backup check $date1 repor$
    rm tmp1.txt
    else
    echo backup failure
    printf "sitename backup failure!" | mail -s "site backup check $date1 repor$
    rm tmp1.txt
    fi
    exit
    

    But this isn't working really well and I ask you if there's some simpler and more powerful way to do it? Basically it just needs to check if file exists with the name starting xyz and was created at date xyz.

    • jasonwryan
      jasonwryan over 9 years
    • mikeserv
      mikeserv over 9 years
      Possibly a core problem w/ the logic here is the $performtw declaration - the var's value is set to the stdout of a pipeline that redirects to a file. Also you neednt call date twice - you can do so only the first time then ${split%.*} the value as needed. But aside from test -s you might like to know most shells support test -nt which compares mod times between two existing files - it fails if either does not exist or if the one on the left side is not newer than the one on the right.