Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many arguments error in bash

Tags:

bash

shell

unix

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?

like image 394
William Oliver Avatar asked Aug 17 '26 03:08

William Oliver


2 Answers

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.

like image 92
anubhava Avatar answered Aug 18 '26 20:08

anubhava


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 ls is simply extraneous.

like image 26
Reinstate Monica Please Avatar answered Aug 18 '26 19:08

Reinstate Monica Please