in Articles

Shell script to show a file and optionally delete it

I needed to open a number of files and depending on the content, delete them. Here is a quick bash script to cat the file and ask a question to delete the file afterwards.

#!/bin/bash

VIEWER="cat"

if [ -d $1 ]
then
     DIR=$1
else
     echo "Enter a directory to clean"
     exit 1
fi

for file in `ls $DIR`
do
     $VIEWER $DIR/$file
     echo -n "Delete file (y/n)? "
     read RESP
     if [ $RESP == "y" ]
     then
          echo "Deleting $DIR/$file"
          rm -f $DIR/$file
     fi
done

You can change the viewer to something else, if you don’t want to use cat, and instead of deleting the file, you might want to move it somewhere else instead.