Home > Enterprise >  For loop working in terminal but not in shell script
For loop working in terminal but not in shell script

Time:12-29

I was trying to rename files.

$ls
1.jpg   12.jpg  15.jpg  18.jpg  3.png  6.jpg  9.png
10.jpg  13.jpg  16.jpg  19.jpg  4.jpg  7.png
11.jpg  14.jpg  17.jpg  2.jpg   5.jpg  8.jpg

From 1.jpg to 01.jpg for files {1..9}.* irrespective of extension. I tried the following for loop in terminal it worked perfectly.

$for i in {1..9}.*;do mv "$i" 0"$i";done

When I wrote the same in shell script it didn't work.

#!/bin/sh
for i in {1..9}.*;do mv "$i" 0"$i";done

It gave the following error

mv cannot stat '{1..9}.*':No such file or directory

I figured that posix shell doesn't support {1..9}.* syntax.

Q:what is the equivalent of this in posix?

-Thank You.

CodePudding user response:

You can use the wildcard pattern [1-9].*.

#!/bin/sh
for i in [1-9].*
do 
    mv "$i" 0"$i"
done
  • Related