【问题标题】:Arguments not found in shell script在 shell 脚本中找不到参数
【发布时间】:2015-03-01 22:42:36
【问题描述】:

我正在尝试为一个类编写我的第一个 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

我正在使用 dash shell。

【问题讨论】:

  • 能否请您显示您输入的命令行,以及您收到的确切错误消息?
  • 你在使用bash吗?
  • @lurker 我将其输入为 './Assign2-1 3 4 5' 对于每个参数重复以下错误消息: ./Assign2-1: 27: ./Assign2-1: numbers[ 0]=3: 未找到 ./Assign2-1: 28: ./Assign2-1: let: 未找到 ./Assign2-1: 29: ./Assign2-1: squares[0]=: 未找到 expr: 语法错误
  • @sputnick 我想我正在使用破折号。它是默认的 Ubuntu shell。
  • 感谢您的帮助。这确实是外壳的问题。如果您再次遇到遇到此问题的人,请提醒他们也更改脚本中的第一行,确保它调用正确的解释器(我没有在上面包含这行代码),因为这仍然给我带来了问题。

标签: shell arguments dash-shell


【解决方案1】:

看来你是初学者,一些不错的开始学习的指点:

常见问题解答: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

【讨论】:

  • 感谢您的建议。最大的问题之一是为课程提供示例的教科书,最后一次更新是在 2003 年。对于我正在学习的 85% 的内容来说,这不是问题,但是 shell 脚本部分可以使用一些补充材料。
【解决方案2】:

Dash 不支持数组,Bash 支持。

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

如果你从控制台运行它:

bash script.sh

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

#!/bin/bash

而不是:

#!/bin/sh

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2016-12-01
    相关资源
    最近更新 更多