我需要编写一个bash脚本,该脚本接收一个数组(N个空格分隔的整数)作为命令行参数,并输出整数的总和。
当我将字符串作为参数传递时,我从expr
中收到一个错误,而我的程序被假定写入了一个以Usage:
开头的错误消息,如下所述在下面。
bash : test.sh hello world
expr: non-integer argument
实现如下:
#!/bin/bash
for i do
sum=$(expr $sum + $i)
done
echo $sum
预期规格如下:
$ bash my-script.sh 1 2 3 4
10
$ bash my-script.sh
Usage:- bash my-script.sh space-separated-integers
$ bash my-script.sh hello world
Usage:- bash my-script.sh space-separated-integers
答案 0 :(得分:2)
#!/usr/bin/env bash
# No arguments
if [[ $# -eq 0 ]]; then
echo "Usage:- bash $0 space-separated-integers" >&2
exit 1
fi
result=0
reg='^[0-9]+$'
# One argument is not a number
for arg in "$@"; do
if ! [[ $arg =~ $reg ]] ; then
echo "Usage:- bash $0 space-separated-integers" >&2
exit 1
else
((result += arg))
fi
done
echo "$result"