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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With