help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Validating files and directories


From: Andreas Kusalananda Kähäri
Subject: Re: Validating files and directories
Date: Sat, 13 Nov 2021 10:33:14 +0100

On Sat, Nov 13, 2021 at 10:06:01AM +0100, Kusalananda Kähäri wrote:
> On Sat, Nov 13, 2021 at 12:22:18AM +0000, irenezerafa via wrote:
> > I am using the following commands to validate a file or directory.
> > 
> > if [[ ! -f "$fl" && ! -d "$fl" ]]; then
> > printf '%s\n' "$fl: File or Directory does not exist"
> > fi
> > 
> > But have noticed that I can use -e to see if there's something by that 
> > name, instead of separately testing -f and -d.
> > Yet I am getting confused between using -a and -e.
> 
> Why would you be confused between -a and -e?  You don't use -a here and
> you never ever need to use it.
> 
> See https://unix.stackexchange.com/questions/147728
> 
> Note that you can't replace your -f and -d tests with -e if you also
> care about files that are not regular files or directories (e.g.
> sockets, block device files, fifos etc.)  A file that -e says exists may
> be neither a regular file nor a directory.
> 
> You could possibly say
> 
>       if [[ -e "$fl" ]]; then
>               if [[ ! -f "$fl" ]] && [[ ! -d "$fl" ]]; then
>                       printf '%s exists but is neither directory nor 
> regular\n' "$fl"
>               else
>                       printf '%s exists and is directory or regular\n' "$fl"
>               fi
>       else
>               printf '%s does not exist\n' "$fl"
>       fi
> 
> The -e test is not a file-type test, while both -f and -d are.

Sorry, I forgot about symbolic links...

        if [[ -e "$fl" ]]; then
                if [[ -f "$fl" ]] || [[ -d "$fl" ]]; then
                        printf '%s exists and is ' "$fl"
                        if [[ -h "$fl" ]]; then
                                printf 'a symbolic link to '
                        fi
                        printf 'a directory or regular file\n'
                else
                        printf '%s exists but is ' "$fl"
                        if [[ -h "$fl" ]]; then
                                printf 'a symbolic link to '
                        fi
                        printf 'neither directory nor regular file\n'
                fi
        elif [[ -h "$fl" ]]; then
                printf '%s is a broken symbolic link\n' "$fl"
        else
                printf '%s does not exist\n' "$fl"
        fi
 

-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]