0
#!/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.

1
  • What is the error? Commented May 7, 2020 at 21:01

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)" ])

4 Comments

regarding the last remark of your answer, I'm not sure it'd work as echo *.txt prints *.txt litteraly if there is no .txt file (but maybe there's some Bash option to change that default behavior)
@ErikMD, Thanks for spotting that error! Now revised with s/echo/ls/, which is lame, but it seems to work...
actually it seems there is a more builtin solution with Bash, using a special option − cf. gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.htmlshopt -s nullglob; if [ "$(echo *.txt)" ]; then echo "file(s) found"; fi
@ErikMD, Good idea, see revised answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.