Search code examples
bashshellif-statementconfirmation

How to Ask User for Confirmation: Shell


I am new to shell, and my code takes two arguments from the user. I would like to confirm their arguments before running the rest of the code. I would like a y for yes to prompt the code, and if they type n for no, then the code will ask again for new arguments

Pretty much, if i type anything when I am asked to confirm, the rest of the code runs anyways. I tried inserting the rest of the code after the first then statement, but that didn't work either. I have also checked my code with ShellCheck and it all appears to be legal syntax. Any advice?

#!/bin/bash

#user passes two arguments 
echo "Enter source file name, and the number of copies: "

read -p "Your file name is $1 and the number of copies is $2. Press Y for yes N for no " -n 1 -r
echo  
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "cloning files...."
fi


#----------------------------------------REST OF CODE

DIR="."

function list_files()
 {
 if ! test -d "$1" 
 then echo "$1"; return;
 fi

 cd ... || $1
 echo; echo "$(pwd)":; #Display Directory name

for i in *
do
if test -d "$i" #if dictionary
then 
list_files "$i" #recursively list files
 cd ..
 else
 echo "$i"; #Display File name
fi

done
}

 if [ $# -eq 0 ]
then list_files .
exit 0
fi

for i in "$@*"
do
DIR=$1 
list_files "$DIR"
shift 1 #To read next directory/file name
done
if [ ! -f "$1" ]                        
then
echo "File $1 does not exist"
exit 1
fi

for ((i=0; i<$2; i++))
do
cp "$1" "$1$i.txt"; #copies the file i amount of times, and creates new files with names that increment by 1
 done

status=$?                                  
if [ "$status" -eq 0 ]
then
echo 'File copied succeaful'
else
echo 'Problem copying'
fi

Solution

  • Moving the prompts into a while loop might help here. The loop will re-prompt for the values until the user confirms them. Upon confirmation, the target code will be executed and the break statement will terminate the loop.

    while :
    do
      echo "Enter source file name:"
      read source_file
    
      echo "Number of copies"
      read number_of_copies
    
      echo "Your file name is $source_file and the number of copies is $number_of_copies."
      read -p "Press Y for yes N for no " -n 1 -r
      if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "cloning files...."
        break ### <<<---- terminate the loop
      fi
      echo ""
    done
    
    #----------------------------------------REST OF CODE