Brian Leishman
Brian Leishman

Reputation: 8575

Bash script removing files unexpectedly

I have this script that I'm running to rename all the files in a folder to "1.png", "2.png", etc, but sometimes it will completely erase (or move the file somewhere else, I have no idea what's happening) the first 10 or so images. This seems to happen whenever there's more than 10 images inside the folder. The script I'm running is below, anyone have any ideas?

#!/bin/bash
cd "$1"
cnt=1
for fname in *
do
if [ "$1" != '/var/www/cydia.stumpyinc.com/theme/images/browse/icons/' ]
then
    mv "$fname" ${cnt}.png
    cnt=$(( $cnt + 1 ))
fi
done

EDIT

I'm also getting this error in the terminal, don't know if it's important or not though

mv: cannot stat `*': No such file or directory

Upvotes: 0

Views: 563

Answers (1)

Ahmed Masud
Ahmed Masud

Reputation: 22402

Your script is bizarre: from your description the correct way of renaming everything to a number should be something like:

#!/bin/bash


error() {
    ec=$1
    shift;
    echo "$@" 1>&2
    exit $ec
}

TARGETDIR="$1"

if [ ! -d $TARGETDIR ] ; then
     error 1 "$TARGETDIR: No such directory"
fi

if [ "$TARGETDIR" = '/var/www/cydia.stumpyinc.com/theme/images/browse/icons/' ] ; then
     error 1 "Cannot process $TARGETDIR"
fi

# Okay let's process stuff now...


cd $TARGETDIR
if [ "$(echo *)" = "*" ] ; then
     error 1 "$TARGETDIR: empty directory"
fi

# calculate zero-padding for the number of files present.

zeros=$(ls -1 | wc -l | wc -c)
cnt=1
for k in * ; do 
    if [ -f "$k" ] ; then
          ext=."$(echo $k | awk -F\\. '{ printf $NF }')"
          fn=$(printf "%0${zeros}d" $cnt)
          echo "Converting $k to ${fn}${ext}"
          mv "$k" "${fn}${ext}"
          cnt=$(($cnt+1)) 
    fi
done

Upvotes: 2

Related Questions