0

我正在尝试为一个类编写我的第一个 shell 脚本。目标是将整数列表作为命令行参数并显示它们的平方和平方和。我收到一个错误,即找不到参数。

这是给出未找到参数的错误的部分:

sumsq=0 #sum of squares  
int=0 #Running sum initialized to 0  
count=0 #Running count of numbers passed as arguments  

while [ $# != 0 ]  
do  
    numbers[$int]=`expr $1`     #Assigns arguments to integers
    let square=`expr $1*$1`     #Operation to square arguments
    squares[$int]=$square       #Calc. square of each argument
    sumsq=`expr $sumsq + $square`   #Add square to total
    count=`expr $count + 1`     #Increment count
    shift               #Remove the used argument
    int=`expr $int + 1`     #Increment to next argument

done

我正在使用破折号外壳。

4

2 回答 2

0

看来您是初学者,一些很好的开始学习指南:

常见问题解答:http: //mywiki.wooledge.org/BashFAQ
指南: http: //mywiki.wooledge.org/BashGuide
参考:http ://www.gnu.org/software/bash/manual/bash.html
http:// /wiki.bash-hackers.org/
http://mywiki.wooledge.org/Quotes
检查您的脚本:http ://www.shellcheck.net/

并且避免人们说要通过tldp.org网站学习,tldp bash 指南已经过时,在某些情况下完全是错误的。

您的代码中有很多可以改进的地方。最好尽快学习好方法。你的代码看起来是 80 年代的 =)


更正经的版本(未测试),做事方式更腼腆:

sumsq=0 #sum of squares  
int=0 #Running sum initialized to 0  
count=0 #Running count of numbers passed as arguments  

while (($# != 0 )); do 
    numbers[$int]=$1            #Assigns arguments to integers array
    square=$(($1*$1))           #Operation to square argument first arg by itself
    squares[$int]=$square       #Square of each argument
    sumsq=$((sumsq + square))   #Add square to total
    count=$((count++))          #Increment count
    shift                       #Remove the used argument
done
于 2015-01-04T03:52:31.847 回答
0

Dash 不支持数组,Bash 支持。

如果您以交互方式运行脚本,您可能没有将 bash 配置为默认 shell,请bash在尝试之前运行。

如果您从控制台运行它:

bash script.sh

如果您使用它的路径(例如./script.sh)运行它,请确保脚本的第一行是:

#!/bin/bash

并不是:

#!/bin/sh
于 2015-01-04T03:26:55.250 回答