0

I need to write a script that would display all files larger than 1M one by one (in the current dir) and after each file displayed to ask the user whether or not he wants to delete it (Y/n), then if he wants to compress it and finally an option to skip it. After the user chooses an action, the next file should be displayed with the same options offered.

That is what I managed to write so far, but the output gives me the name of the first file (One by one thing works) and gives 'Invalid input' on the following line.

#!/bin/bash

find . -maxdepth 1 -type f -size +1M | while read -r output; 
do
    echo ${output};

    read -r -p "Would you like to delete the file? [Y/n] " input

    case $input in
    [yY][eE][sS]|[yY])
        echo "The file has been deleted!"
        ;;
    [nN][oO]|[nN])
        ;;
    *)
        echo "Invalid input..."
        exit 1
        ;;
    esac
done

It is clear to me that read -r -p input does not work in the while loop that already contains read -r output, but I don't see what I could do in this situation.

1
  • FWIW, you could make some improvements to the script without changing what it does. Here's how I would write it: pastebin.com/bCVypq74
    – wjandrea
    Mar 21, 2019 at 14:51

2 Answers 2

1

Use a function and call it like this find [...] -exec bash -c 'myFunction "$1"' _ {} \;.

e.g. something like this:

#!/bin/bash

rmziporskip(){
    printf 'What should I do with %s ?\n' "$1"
    select action in remove zip skip; do
        case $action in
            remove)
                    rm "$1";
                    echo "The file has been deleted!"
                    ;;
            zip)
                    zip "$1.zip" "$1"
                    rm "$1";
                    echo "The file has been zipped and the original deleted!"
                    ;;
            *)
                    echo "The file has been skipped!"
                    ;;
        esac
        break;
    done
}


export -f rmziporskip
find . -maxdepth 1 -type f -size +1M -exec bash -c 'rmziporskip "$1"' _ {} \;
0

Yes there is a dual use of std input read.
In that case, you can simply read from the controlling terminal device:

at line 7, add </dev/tty

read -r -p "Would you like to delete the file? [Y/n] " input</dev/tty

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .