Reputation: 21
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
Upvotes: 0
Views: 2140
Reputation: 881273
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.
Upvotes: 1
Reputation: 123410
# 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)
Upvotes: 1