Adam Chippy Lowe
Adam Chippy Lowe

Reputation: 3

Bash script unable to run (too many arguments)

#!/bin/bash    
if [ -e *.txt ]                                                                                                         then
            rm *.txt
            echo "removing previous files"
    else
            echo "files already deleted"
    fi

I'm trying to remove all txt files in my current directory if I have more than 1 txt file I get an error. Not quite sure whats happening.

Upvotes: 0

Views: 113

Answers (2)

agc
agc

Reputation: 8446

Keeping the if ... fi logic, there's no need for an -e test here. Unix utils are themselves designed to return exit codes, and in this case it's simpler to test the result of rm itself:

if rm *.txt 2> /dev/null
then
    echo "removing previous files"
else
    echo "files already deleted"
fi

But even though it's not needed, do note that a separate test could be made to work like so:

if [ "$(ls *.txt)" ]

...or in pure bash, (no external util like ls needed), if we temporarilly set the nullglob option:

if (shopt -s nullglob; [ "$(echo *.txt)" ])

Upvotes: 1

ErikMD
ErikMD

Reputation: 14753

If you have, say, two files 1.txt and 2.txt, your code basically leads to:

if [ -e 1.txt 2.txt ]
…

which just raises a syntax error, because -e expects a single argument.

You could rely on some CLI tool such as find, but maybe you don't need the if in the first place?

Namely something like:

rm -f *.txt

to avoid failing in case there is no *.txt file,

otherwise:

rm -f -v *.txt

if you also want to get some log of the removed files.

Upvotes: 3

Related Questions