0

I need to write a basic program which would find the files which have odd (uneven) size in bytes in user specified directory and then rename them. I wrote a code but can't figure it out what's wrong with it since I have only just began to programm bash scripts... I have 3 files in my directory and here are the errors I'am getting for them:

./Untitled: line 18: AppIcon.icns: command not found

mv: cannot stat ‘AppIcon.icns’: No such file or directory
./Untitled: line 18: AssociatedVm.txt: command not found

mv: cannot stat ‘AssociatedVm.txt’: No such file or directory
./Untitled: line 18: Info.plist: command not found

mv: cannot stat ‘Info.plist’: No such file or directory

My script Code:

#!/bin/bash

n=0

echo “Specify directory” 

read directory

if [ -d $directory ]; then

         echo “Directory found”

else 
    echo “Directory not found” 

exit 0

fi

for file in $( ls $directory );

do

fsize=$(stat "$directory/$file" -c %s)


if [ $((fsize%2))=1 ]; then 


mv "$directory/$file" "$directory/$file.odd"


n=$((n + 1))


fi
 done

echo ”Number of renamed files: $n ”  
1
  • Don't parse ls. Use shell globs. And quotes. Commented Oct 19, 2013 at 14:59

1 Answer 1

2

I think you meant

fsize=$(stat "$file" -c %s)

but you wrote

fsize=stat "$file" -c %s

Also, you need to use the absolute path($directory/$file) instead of $file alone if you are running the script from a directory which is not $directory.

Bash uses -eq for integer comparison, so you should also change

if [ $((fsize%2))=1 ]; then

to

if [ $((fsize%2)) -eq 1 ]; then

What is the -c %s for? I don't see a -c option in the stat man page. Did you mean -f? (EDIT: Ok I was looking at the Mac stat command (which is BSD). The stat in GNU version uses -c for format specification)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it fixed the errors (I updated the code). HOVEWER, for some reason now it renames all of the files in directory. How could I make it rename only the ones with uneven(odd) size? I confused myself right now lol. –
Ah, bash uses -eq for integer comparison, so you should change $((fsize%2))=1 to $((fsize%2)) -eq 1 (updated the answer as well).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.