0
#!/usr/bin/ksh
i=1   
while [ "$i" -lt 121 ]   
do  
    if [ $i -lt 100 ]  
    then  
        if [ $i -lt 10 ]   
        then   
            i=00$i   
        else   
            i=0$1    
        fi   
    fi   
    echo "fla${i}"  
    i=' expr $i+1 '  
done  
exit 0

Why does this script result in an error "Too many arguments"?

dr_
  • 28,763
  • 21
  • 89
  • 133
user2310119
  • 11
  • 1
  • 2
  • 1
    This is [Bash Pitfall #4](http://mywiki.wooledge.org/BashPitfalls#A.5B_.24foo_.3D_.22bar.22_.5D), (save that link, you'll need it if you face other issues with shell programming. You had ksh instead of bash but many parts will apply). Also see the [difference between `[` and `[[`](http://unix.stackexchange.com/q/56655/170373) – ilkkachu Mar 09 '17 at 10:25
  • You can use `set -x` to the shebang line to enable verbose debug mode to see what exactly is happening while executing the script. – Erathiel Mar 09 '17 at 10:27
  • 1
    This can replace your script: `for i in {1..128}; do printf "fla%03d\n" $i; done` – glenn jackman Mar 09 '17 at 17:44
  • Even simpler: `printf "fla%03d\n" {1..128}` – Gordon Davisson Mar 09 '17 at 21:58

2 Answers2

2

i=' expr $i+1 ' is not incrementing i, it assigns i a value of ' expr $i+1 '.

On the next iteration of the loop you run [ $i -lt 100 ]. Since i is not embraced in double quotes, this expands to [ expr '$i+1' -lt 100 ]. [ is actually a command, and you have given it too many arguments due to the reason above.

If you replace i=' expr $i+1 ' with i=$(($i + 1)), your code should work.

Edit:

It seems that at least Bash will have issues with the number 008, it interprets it as octal. You need to assign 00$i, 0$i and $i to another variable (or echo "fla00$i" etc) if you get some error after 008.

In this case, you'll need to do something when i >= 100.

This is what I would do:

i=1
while [ $i -lt 121 ]; do
    if [ $i -ge 100 ]; then
        echo fla$i
    elif [ $i -ge 10 ]; then
        echo fla0$i
    else
        echo fla00$i
    fi
    i=$(($i + 1))
done
Oskar Skog
  • 377
  • 1
  • 3
  • 13
1

Your entire script intention is to do exactly this: seq -f 'fla%03.0f' 1 128

As to the shell programming:

i=0$1 should probably become i="0$i"

' expr $i+1 ' should become $( expr "$i" + 1 )

Note the spaces required by expr. This won't work $( expr "$i"+1 )

kubanczyk
  • 1,248
  • 9
  • 19