用于 if 条件的 Shell 脚本太多参数 [英] Shell Script Too Many Arguments for if condition

查看:70
本文介绍了用于 if 条件的 Shell 脚本太多参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的脚本执行以下操作;

My current script does the following;

它将整数作为命令行参数,从 1 到 N 开始,它检查数字是否可以被 3、5 或两者整除.它只是打印出 3 的 Uc、5 的 Bes 和 3,5 的 UcBes.如果命令行参数为空,则执行相同的操作,但循环进行到 1 到 20.

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.

我遇到了这个错误第 11,15 和 19 行的参数太多".

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

代码如下:

#!/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

推荐答案

注意 [ 实际上是 shell 中内置的 test 的同义词(尝试 which [ 在你的终端),而不是像其他语言那样的条件语法,所以你不能这样做:

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

这篇关于用于 if 条件的 Shell 脚本太多参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆