Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash reading users y/n answer does not work (read command inside while loop reading find output)

Tags:

linux

bash

I have a problem here. Seems like my Bash script is ignoring everything that is between do and done. Don't know why, maybe you will see the problem. Thanks in advance.

katalogas=$1
find $katalogas -type f -mtime +3 | while read $failai
do
read -p "Run command $foo? [yn]" answer
if [[ $answer = y ]] ; then
  rm $failai
fi
done
like image 675
demboz11 Avatar asked May 03 '15 20:05

demboz11


2 Answers

Try to replace

read -p "Run command $foo? [yn]" answer

by

read -p "Run command $foo? [yn]" answer </dev/tty

to avoid reading from stdin.

Update with Will's suggestion:

katalogas="$1"
read -p "Run command $foo? [yn]" answer
if [[ $answer = y ]] ; then
  find "$katalogas" -type f -mtime +3 | while read failai
  do
    rm "$failai"
  done
fi
like image 80
Cyrus Avatar answered Sep 30 '22 05:09

Cyrus


So the first problem I see is that your while read $failai should be while read failai (without the $). Try this:

katalogas="$1"
find "$katalogas" -type f -mtime +3 | while read failai; do
    read -p "Run command ${foo}? [yn]" answer
    if [[ "$answer" = "y" ]]; then
        echo labas
    fi
done

As far as prompting for yes or no, though, I usually use something like this:

function prompt_yn()
{
    local default=""
    local prompt="y/n"
    local input

    # If $2 specifies a default choice, configure options accordingly.
    if [[ "${2:-}" = "Y" ]]; then
        prompt="Y/n"
        default="Y"
    elif [[ "${2:-}" = "N" ]]; then
        prompt="y/N"
        default="N"
    fi

    # Prompt the user until they give an appropriate answer.
    while true; do
        read -p "$1 [${prompt}] " input
        [[ -z "$input" ]] && input="$default"

        case "$input" in
            [Yy]* ) return 0;;
            [Nn]* ) return 1;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

So, if you used the code above, your code would look like this:

katalogas="$1"
find "$katalogas" -type f -mtime +3 | while read failai; do
    if prompt_yn "Run command ${foo}?"; then
        echo labas
    fi
done

You can also add a "Y" or a "N" after the "Run command ${foo}?" to specify a default value if the user just presses Enter.

EDIT: It seems I missed the point about part of this. Cyrus's answer is the solution to the read not working inside the loop. This StackOverflow post explains it well also. However, based on your comment, @semkius, it seems you only want to ask the question once, outside of the loop.

like image 24
Will Avatar answered Sep 30 '22 05:09

Will