bash 中的参数错误太多

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21253969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:19:11  来源:igfitidea点击:

Too many arguments error in bash

bashshellunix

提问by William Oliver

I am writing a script to delete all files in a directory for practice. I am using quotes around my variables, and yet I am still getting the following error:

我正在编写一个脚本来删除目录中的所有文件以进行练习。我在我的变量周围使用引号,但我仍然收到以下错误:

/usr/local/bin/deleteall: line 6: [: too many arguments
/usr/local/bin/deleteall: line 11: [: too many arguments 

Here is my code:

这是我的代码:

#!/bin/bash
#Deletes all files in the current directory

read -p "You are about to delete all files in $(pwd). Are you sure you want to do this? y/n" yn
echo $yn
if [ [ "$yn" = "y" ] -o [ "$yn" = "Y" ] ] ; then
        for i in `ls`; do
                rm $i
        done
        exit;
elif [ [ "$yn" = "n" ] -o [ "$yn" = "N" ] ] ; then
        exit;
else
        read -p "Please enter y (yes) or n (no)"
        exit;
fi

And this is the entire output:

这是整个输出:

You are about to delete all files in <my dir>. Are you sure you want to do this? y/nn
n
/usr/local/bin/deleteall: line 6: [: too many arguments
/usr/local/bin/deleteall: line 11: [: too many arguments
Please enter y (yes) or n (no)n

What am I doing wrong?

我究竟做错了什么?

回答by anubhava

This line appears to be problem:

这一行似乎有问题:

if [ [ "$yn" = "y" ] -o [ "$yn" = "Y" ] ] ; then

You can replace this with:

您可以将其替换为:

if [[ "$yn" == [yY] ]]; then

PS:Do same for the line where you check n or N.

PS:对您检查的行执行相同操作n or N

回答by Reinstate Monica Please

You can't nest []. It's literally interpreting the nested brackets as arguments, and printing an error that you have too many.

你不能筑巢[]。它实际上将嵌套的括号解释为参数,并打印出您有太多的错误。

Just this will work

只是这会奏效

if [ "$yn" = "y" -o "$yn" = "Y" ]; then

Another alternate syntax using double brackets and same logic

另一种使用双括号和相同逻辑的替代语法

if [[ $yn == "y" || $yn == "Y" ]]; then 

Also

for i in `ls`; do
  rm $i
done

Should really be

真的应该

for i in *; do
  [ -f "$i" ] && rm $i
done

So it only tries to remove regular files (you will get errors for dirs, unless you overwrote rm, and you can decide what you want to do with symlinks). And lsis simply extraneous.

因此它只会尝试删除常规文件(除非您覆盖了 dirs,否则您将收到错误消息rm,并且您可以决定要使用符号链接做什么)。并且ls是无关紧要的。

回答by MLSC

this is what you want:

这就是你想要的:

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]
then
     for i in `ls`; do
      rm -rf $i
done
fi

if [[ $REPLY =~ ^[Nn]$ ]]
then
     #do what you want
done
fi