简体   繁体   中英

Check if a file exists with the same name as a directory

I'm trying to make a script that will determine whether a '.zip' file exists for each sub-directory. For example the directory I'm working in could look like this:

/folder1
/folder2
/folder3
folder1.zip
folder3.zip

The script would then recognise that a '.zip' of "folder2" does not exist and then do something about it.

So far I've come up with this (below) to loop through the folders but I'm now stuck trying to convert the directory path into a variable containing the file name. I could then run an if to see whether the '.zip' file exists.

#!/bin/sh

for i in $(ls -d */);
do
    filename= "$i" | rev | cut -c 2- | rev
    filename="$filename.zip"
done
# No need to use ls
for dir in */
do
  # ${var%pattern} removes trailing pattern from a variable
  file="${dir%/}.zip"
  if [ -e "$file" ]
  then
    echo "It exists"
  else
    echo "It's missing"
  fi
done

Capturing command output wasn't necessary here, but your line would have been:

# For future reference only
filename=$(echo "$i" | rev | cut -c 2- | rev)

You can do it with something like:

#!/bin/sh

for name in $(ls -d */); do
    dirname=$(echo "${name}" | rev | cut -c 2- | rev)
    filename="${dirname}.zip"
    if [[ -f ${filename} ]] ; then
        echo ${dirname} has ${filename}
    else
        echo ${dirname} has no ${filename}
    fi
done

which outputs, for your test case:

folder1 has folder1.zip
folder2 has no folder2.zip
folder3 has folder3.zip

You can do it without calling ls and this tends to become important if you do it a lot, but it's probably not a problem in this case.

Be aware I haven't tested this with space-embedded file names, it may need some extra tweaks for that.

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