HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMinor

Bash script to clear files not matching a given extension

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptextensionfilesclearnotgivenbashmatching

Problem

Using LaTeX creates a bunch of auxiliary files like foo.aux, foo.log, etc. Sometimes, I want to create a clean run of my document. I usually manually execute this in the terminal as

$ ls foo*
foo.tex
foo.aux
foo.log
foo.bbl
foo-blx.bib
$ rm foo{.aux,.log,.bbl,-blx.bib}


This works fine. However, it is error-prone and I don't want to accidentally erase my .tex file. So I added this function to my ~/.bashrc:

# Delete all non-TeX files
# invoke as: cleantex foo
# where: foo.tex, foo.aux, foo.log, etc. are files in directory
cleantex () {
    if [ -n "$1"]; then
        name = $(basename -s ".tex" "$1")
        rm -f $name{.!(*tex),-blx.bib}
    fi  
}


My question is about the key line

rm -f $name{.!(*tex),-blx.bib}


that actually executes the script.

Is this line well-written? What might I improve here?

Solution

My real concerns with the script are:

  • cleantex path/to/file.tex will not delete files in that path, but in the current directory.



  • you should check the actual .tex file exists before you delete all the things around it.



  • the brace-expansion is unnecessarily complicated...... especially when combined with the extended glob !(*tex). I would manually resolve the brace-expansion so that there is only one complicated operation on that line.



  • I would use actual glob-expansion and only delete existing files.... and not use the -f option on rm (which does more than just suppress the error message if files do not exist....)

Context

StackExchange Code Review Q#45556, answer score: 6

Revisions (0)

No revisions yet.