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"?

  • 1
    This is Bash Pitfall #4, (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 [[ – ilkkachu Mar 9 '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 9 '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 9 '17 at 17:44
  • Even simpler: printf "fla%03d\n" {1..128} – Gordon Davisson Mar 9 '17 at 21:58
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
| improve this answer | |
  • Try elif instead of else if – glenn jackman Mar 9 '17 at 17:46
  • @glennjackman: That sure would look nicer. Thanks. – Oskar Skog Mar 9 '17 at 17:47
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 )

| improve this answer | |
  • Or printf 'fla%03d\n' {1..121} (or in bash zsh just printf '%s\n' fla{001..121} ) – dave_thompson_085 Mar 9 '17 at 15:17
  • 1
    don't call out to expr, do i=$((i+1)) or ((i++)) and let ksh handle the addition – glenn jackman Mar 9 '17 at 17:42
  • The range is 1...120. – Oskar Skog Mar 9 '17 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.