Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash~如果参数1包含负整数或它退出的字符串,我怎么能这样做呢_Bash_Shell - Fatal编程技术网

Bash~如果参数1包含负整数或它退出的字符串,我怎么能这样做呢

Bash~如果参数1包含负整数或它退出的字符串,我怎么能这样做呢,bash,shell,Bash,Shell,这是我的脚本,我在elif语句中遇到了问题。如果用户输入非负整数作为参数1或字符串,我需要它退出 #!/bin/sh n="0" m="$1" if test $# != "2" then echo "Usage: ./echon.sh <number of lines> <string>" exit 1 elif [ $1 -eq "[^0-9]" ] || [ $1 = "[a-zA-Z]" ] then echo "./echon.sh:

这是我的脚本,我在elif语句中遇到了问题。如果用户输入非负整数作为参数1或字符串,我需要它退出

#!/bin/sh
n="0"
m="$1" 
if test $# != "2"
then
    echo "Usage: ./echon.sh <number of lines> <string>"
    exit 1
elif [ $1 -eq "[^0-9]" ] || [ $1 = "[a-zA-Z]" ]
then
    echo "./echon.sh: argument 1 must be a non-negative integer"
    exit 1
else
    while [ "$n" -lt  "$m" ]
    do
    echo "$2"
    n=$(($n + 1))
    done
fi
#/垃圾箱/垃圾箱
n=“0”
m=“$1”
如果测试$#!="2"
然后
echo“用法:./echon.sh”
出口1
elif[$1-eq“[^0-9]”]| |[$1=“[a-zA-Z]”]
然后
echo.“/echon.sh:参数1必须是非负整数”
出口1
其他的
而[“$n”-lt“$m”]
做
回音“$2”
n=$($n+1))
完成
fi
快速重写

#!/bin/bash
shopt -s extglob
if (( $# != 2 )); then
    echo "Usage: $0 <number of lines> <string>"
elif [[ $1 != 0 && $1 != [1-9]*([0-9]) ]]; then
    echo "$0: argument 1 must be a non-negative integer"
else
    n=0
    while (( n < $1 )); do
        echo "$2"
        ((n++))
    done
fi
#/bin/bash
shopt-s extglob
如果($#!=2));然后
echo“用法:$0”
elif[[$1!=0&&$1!=[1-9]*([0-9])];然后
echo“$0:参数1必须是非负整数”
其他的
n=0
而(n<1美元);;做
回音“$2”
((n++)
完成
fi
注释

  • 使用
    […]]
    进行字符串比较
  • 对算术表达式使用
    (…)
  • 使用扩展globbing匹配非负整数(强制非零数字不以0开头,以避免可能的无效八进制数字)

将您的
elif
行替换为以下内容:

elif echo $1 | grep -qv "^[0-9][0-9]*"

-eq
用于数值比较,而不是字符串或regexpAnd
=
用于字符串比较,而不是regexp。我想当有人输入负数而不是非负数时,您应该退出。+1使用模式匹配与
*(…)
很好。我想你可以把
$1!=0&
part。此外,您可以使用
*([0-9])
而不设置
extglob
。bash的哪个版本允许您在不使用extglob的情况下使用该语法?
$1!=允许“0”作为有效的非负整数需要0
:否则我明确禁止以“0”开头的数字。