如何添加命令行参数数组而不输出到Bash中的stderr

问题描述 投票:1回答:1

我需要编写一个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
python bash
1个回答
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"
© www.soinside.com 2019 - 2024. All rights reserved.