0

From my code below, I am to search for files of size zero, and prompt the user to delete them, if they so wish. However I am lost as the script should allow for directories to be specified as command line parameters. I must use the current directory as default, if no directory is specified on the command line. I think I am on the right track, but can not seem to figure out how to prompt the user to enter the path to the file he wishes to delete.

#!/bin/bash

ls -lR | grep '^-' | sort -k 5 -rn

echo "Files of size zero, relative to current directory, are as follows:"
find . -size 0 -print

echo "Would you like to delete the files of size zero?: Type yes or no"
read answer

if [[ $answer == "yes" ]]
then
    find . -type f -empty -delete
    echo "List of files with size zero files deleted:"
    ls -lR | grep '^-' | sort -k 5 -rn

else
    echo "User wishes to not delete files"
fi
Herm
  • 1
  • Note I assume that the ls line are just there for debug. However you will not get a list of deleted files, by looking at existing files (the echo and ls, in the then clause). – ctrl-alt-delor Jul 02 '18 at 21:52
  • Note I assume that the ls line are just there for debug. Do not tell the user ”User wishes to not delete files”, they know (and this is very un-Unix). – ctrl-alt-delor Jul 02 '18 at 21:52
  • Also to make the script nicer (easier to use), create two modes: list zero size files, and remove zero size files (this is easier to use than an interactive script). – ctrl-alt-delor Jul 02 '18 at 21:54

1 Answers1

3

You would use

topdir=${1:-.}

This would set the topdir variable to the first command line argument, unless it was missing or empty, in which case it would be set to .. You would then use "$topdir" in your commands. Remember to double quote it.

You would not prompt the user for the paths to the files to delete, you are already using find for that:

find "$topdir" -type f -empty -delete

If you did want a prompt for every file, you would use

find "$topdir" -type f -empty -ok rm {} ';'

Style comments:

  • One usually output prompts to the user on standard error:

    echo "Would you like to delete the files of size zero?: Type yes or no" >&2
    read answer
    

    or

    read -p "Delete files (yes/no): " answer
    
  • You mix -size 0 and -empty in your two find invocations.

Kusalananda
  • 333,661