0

This is a beginner question: I'm trying to write a .sh file to automatically rename files in a directory.

The file would look something like

for fileName in directory
do
    mv fileName "NewPrefix"+fileName
done

I'm trying to figure out how to write the for fileName in directory part.

I tried the following:

dir = '.'
for fileName in dir

This is working, but whenever I run this script, I get dir: cannot access =: No such file or directory.

Why?

1 Answer 1

1

There are several problems with your code:

  • Bash variables are used with $VAR, note the $ in front. If you omit the dollar sign, it is treated like a regular string.
  • Bash filename globbing needs a wildcard (*, ?, etc.). Your example of . would match the folder ., which is the current folder.
  • Variables are set with VAR=VALUE. There is no space around the equals sign. VALUE must be quoted if it has spaces.
  • String concatenation occurs automatically. The + sign inserts a literal + at that position.
  • Variables should always be used surrounded with double quotes unless you have a reason not to.

With these points in mind, here is a working version of your script.

cd /path/to/folder

for file in ./*
do
    mv "$file" "NewPrefix$file"
done

If conditions

If conditions are used like so:

if [[ "$file" == "New"* ]]
then
    # Do something here
fi

Note that the asterisk is outside the double quotes.

12
  • I can't vote up because I don't have enough points but thanks a bunch!
    – teaLeef
    Dec 28, 2013 at 2:32
  • will do (I need to wait five more minutes to accept an answer). I have one more question please: What if, instead of renaming my files "New..." I wanted to do the contrary (I have "New.." files I want to rename without the "New". I tried i(3:end) but it doesn't work...
    – teaLeef
    Dec 28, 2013 at 2:34
  • @teaLeef Where are you getting these examples? They are not for bash. To answer your second question though, you need to do mv "$file" "${file#???}" as the mv line in my code. This will trim the first 3 characters from the file name.
    – kiri
    Dec 28, 2013 at 2:39
  • Actually I had never written bash scripts before, so I'm trying to inspire from other programming languages. Thanks though!
    – teaLeef
    Dec 28, 2013 at 2:40
  • 1
    @teaLeef Bash is more of a scripting language, so its syntax differs from languages like C or Python. If you're getting started, I might suggest this tutorial: mywiki.wooledge.org/BashGuide for teaching you correct syntax and style.
    – kiri
    Dec 28, 2013 at 2:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .