将文件名作为参数传递到脚本中。没有这样的文件或目录

发布于 2024-12-09 19:27:42 字数 527 浏览 0 评论 0原文

我对 shell 脚本编写比较陌生,几天来我一直被这个错误困扰。我正在尝试读取包含字符串和数字列表的文件的内容,对其进行格式化,然后输出低于 50 的数字。

但是,所有命令在键入 shell 时都可以工作;在脚本中,当我尝试将文件名作为参数传递时,我不断收到“没有这样的文件或目录”错误。

这是有问题的函数:

 belowFifty(){
    count=0
    numbers=`cut -d : -f 3 < "$2"` #here is where the error occurs
    for num in $numbers
    do
      if ((num<50));
      then
      count=$((count+1))
      fi
    done
    echo $count
}

编辑:抱歉,我忘记提及该脚本做了几件事。 $1 是选项,$2 是文件。我这样称呼它:

./script.sh m filename

I'm relatively new to shell scripting and I've been stuck on this error for a couple days now. I'm trying to read in the contents of a file containing a list of strings and numbers, format it, and output the number of numbers below 50.

All the commands work when typed into the shell, however; in the script when I try and pass the filename in as an argument I keep getting a "No such file or directory" error.

Here is the function in question:

 belowFifty(){
    count=0
    numbers=`cut -d : -f 3 < "$2"` #here is where the error occurs
    for num in $numbers
    do
      if ((num<50));
      then
      count=$((count+1))
      fi
    done
    echo $count
}

edit: sorry I forgot to mention the script does a couple things. $1 is the option, $2 is the file. I'm calling it like so:

./script.sh m filename

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稚然 2024-12-16 19:27:42

尝试:

${2? 2 arguments are required to function belowFifty}
numbers=$( cut -d : -f 3 < $2 )

我怀疑问题是您正在调用该函数
并且没有指定第二个参数。在函数内,
$2 是传递给函数的参数,而不是参数
传递给主脚本。

Try:

${2? 2 arguments are required to function belowFifty}
numbers=$( cut -d : -f 3 < $2 )

I suspect the problem is that you are calling the function
and not specifying the 2nd argument. Within the function,
$2 is the argument passed to the function, and not the argument
passed to the main script.

-柠檬树下少年和吉他 2024-12-16 19:27:42

您指定“$2”;传递给函数并被忽略的 "$1" 中有什么内容?我强烈怀疑您正在尝试打开名称为空字符串的文件,但不存在这样的文件 - 因此出现错误消息。推论是您可能打算引用 "$1"
如果是这样,您可能应该这样写:

numbers=$(cut -d : -f 3 < "$1")

通常应避免反引号符号,而使用 $(...)

You specify "$2"; what's in the "$1" that's passed to the function and ignored? My strong suspicion is that you are trying to open the file with an empty string as the name, and there is no such file - hence the error message. The corollary is that you probably intended to reference "$1".
If so, you should probably write:

numbers=$(cut -d : -f 3 < "$1")

The back-tick notation should usually be avoided in favour of $(...).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文