Shell Script Too Many Arguments for if condition

时光怂恿深爱的人放手 提交于 2020-05-15 07:56:39

问题


My current script does the following;

It takes integer as a command line argument and starts from 1 to N , it checks whether the numbers are divisible by 3, 5 or both of them. It simply prints out Uc for 3, Bes for 5 and UcBes for 3,5. If the command line argument is empty, it does the same operation but the loop goes to 1 to 20.

I am having this error "Too many arguments at line 11,15 and 19".

Here is the code:

#!/bin/bash

if [ ! -z $1 ]; then
    for i in `seq 1 $1`
    do
        if [ [$i % 3] -eq 0 ]; then
            echo "Uc"
        elif [ i % 5 -eq 0 ]; then
            echo "Bes"
        elif [ i % 3 -eq 0 ] && [ i % 5 -eq 0 ]
        then
            echo "UcBes"
        else
            echo "$i"
        fi
    done
elif [ -z $1 ]
then
    for i in {1..20}
    do
        if [ i % 3 -eq 0 ]
        then
            echo "Uc"
        elif [ i % 5 -eq 0 ]
        then
            echo "Bes"
        elif [ i % 3 -eq 0 ] && [ i % 5 -eq 0 ]
        then
            echo "UcBes"
        else
            echo "$i"
        fi
    done
else
    echo "heheheh"
fi

回答1:


Note that [ is actually synonym for the test builtin in shell (try which [ in your terminal), and not a conditional syntax like other languages, so you cannot do:

if [ [$i % 3] -eq 0 ]; then

Moreover, always make sure that there is at least one space between [, ], and the variables that comprise the logical condition check in between them.

The syntax for evaluating an expression such as modulo is enclosure by $((...)), and the variable names inside need not be prefixed by $:

remainder=$((i % 3))
if [ $remainder -eq 0 ]; then



回答2:


You should probably use something like :

if [ $(($i % 3)) -eq 0 ]

instead of

if [ $i % 3 -eq 0 ]
if [ [$i % 3] -eq 0 ]



回答3:


Your script could be greatly simplified. For example:

#!/bin/sh

n=0
while test $(( ++n )) -le ${1:-20}; do
  t=$n
  expr $n % 3 > /dev/null || { printf Uc; t=; }
  expr $n % 5 > /dev/null || { printf Bes; t=; }
  echo $t
done

gives slightly different error messages if the argument is not an integer, but otherwise behaves the same.



来源:https://stackoverflow.com/questions/13405893/shell-script-too-many-arguments-for-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!