Home > other >  bash script can't check file exists
bash script can't check file exists

Time:01-20

Hello everybody: I have a bash script that check if a file exists and with that information create a new file. The part of the script with the problem is this..

#!/bin/bash 
FECHA=$(date  %Y-%m-%d)
FECHAD=$(date  %d)
FECHAM=$(date  %m)
FECHAA=$(date  %Y)

DIRECTORY="/home/usuario/Build_WRF/DATA/"
FILE1=$DIRECTORY"GFS_24"
FILE2=$DIRECTORY"GFS_48"
FILE3=$DIRECTORY"GFS_72"
FILE4=$DIRECTORY"GFS_96"
FILE5=$DIRECTORY"GFS_120"
FILE6=$DIRECTORY"GFS_144"
FILE7=$DIRECTORY"GFS_168"
FILE8=$DIRECTORY"GFS_192"
FILE9=$DIRECTORY"GFS_216"
FILE10=$DIRECTORY"GFS_240"

if [ -f $FILE10 ]; then
        dias="10 days"
        echo $dias
elif [ -f $FILE9 ]; then
        dias="9 days"
        echo $dias
elif [ -f $FILE8 ]; then
        dias="8 days"
        echo $dias
elif [ -f $FILE7 ]; then
        dias="7 days"
        echo $dias
elif [ -f $FILE6 ]; then
        dias="6 days"
        echo $dias
elif [ -f $FILE5 ]; then
        dias="5 days"
        echo $dias
elif [ -f $FILE4 ]; then
    dias="4 days"
        echo $dias
elif [ -f $FILE3 ]; then
    dias="3 days"
        echo $dias
elif [ -f $FILE2 ]; then
    dias="2 days"
        echo $dias
elif [ -f $FILE1 ]; then
    dias="1 day"
        echo $dias
else
    exit
fi

FECHAF=$(date  %Y-%m-%d --date="$dias")
FECHAFD=$(date  %d --date="$dias")
FECHAFM=$(date  %m --date="$dias")
FECHAFA=$(date  %Y --date="$dias")

The files exists, for example today I have the file GFS_72, the script should return 3 days, but return nothing. I'm missing something. Cheers.

CodePudding user response:

I tried your script and it worked for me.

Please check that /home/usuario/Build_WRF/DATA/GFS_72 actually exists and the directory /home/usuario/Build_WRF/DATA/ is readable and executable as the user the script is executing as.

For instance, as a debugging technique, insert at the top of the script:

ls -la /home/usuario/Build_WRF/DATA/ || {
    echo "Directory not readable as user $USER" >&2
    id
    exit 1
}

Further style issues / Bash tips:

When using [...], you should always quote the arguments to prevent split on space.

if [ -f "$FILE10" ]; then
        dias="10 days"
        echo "$dias"
elif ...

If you know this is going to be running in Bash, you should use [[...]] instead, where you don't have to use quoting (except on the RHS of =).

[[...]] is also marginally faster than [...] in most cases, and it has more features like glob comparisons, regex, and more.

if [[ -f $FILE10 ]]; then
        dias="10 days"
        echo "$dias"
elif ...

CodePudding user response:

Or perhaps, to avoid the ifs

dias="$(( $(echo $DIRECTORY/GFS_* | sed 's![^ ]*GFS_!!g; s! !\n!g' | sort -n | tail -n 1) / 24 )) days"
  • Related