4

I wrote a small script that should rename some files in a directory for me.

#!/bin/bash

a=1
for i in *.jpg ; do
        new=$(printf "%04d.jpg" "$a")
        mv "$i" "$new"
        let a=a+1
done

#end of file

After running the script is says this: "mv: command not found"

How come there are no error outputs when I run the code directly on the shell like this:

for i in *.jpg ; do new=$(printf "%04d.jpg" "$a") ; mv $i $new ; let a=a+1 ; done
Simona
  • 63
  • 1
  • 1
  • 4
  • 5
    Make sure you are not creating / setting a variable called `$PATH` anywhere in the script – arco444 Dec 04 '15 at 16:01
  • 2
    BTW, this is why the POSIX standard suggests that applications use lower-case names for their own environment variables (and thus shell variables, since they share a namespace); it prevents mistakenly overriding variables in the namespace reserved for system use. See fourth paragraph of http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html – Charles Duffy Dec 04 '15 at 16:15
  • 1
    Also check that you don't have any control characters in that script: `od -c myscript.sh` – glenn jackman Dec 04 '15 at 16:19

1 Answers1

15

It probably is a matter of PATH setting. The /bin directory should be inside your $PATH

For debugging purposes, add

echo PATH is $PATH

at start of your script, and perhaps put #!/bin/bash -vx as your script's first line. See this, execve(2), bash(1).

As a workaround, replace

         mv "$i" "$new"

with

         /bin/mv "$i" "$new"

See mv(1)

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    I had the same issue and had accidentally trampled all over my PATH variable by using it as a variable in my script. This helped me track down the issue, much obliged! – Daniel Black Mar 04 '22 at 20:26