如何要求用户确认:Shell

How to Ask User for Confirmation: Shell

我是 shell 的新手,我的代码接受用户的两个参数。我想在 运行 其余代码之前确认他们的论点。我想要一个 y 表示是来提示代码,如果他们键入 n 表示否,那么代码将再次询问新参数

差不多,如果我在被要求确认时键入任何内容,其余代码仍然会运行。我尝试在第一个 then 语句之后插入其余代码,但这也不起作用。我还用 ShellCheck 检查了我的代码,它似乎都是合法的语法。有什么建议吗?

#!/bin/bash

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

read -p "Your file name is  and the number of copies is . 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 "" 
 then echo ""; return;
 fi

 cd ... || 
 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= 
list_files "$DIR"
shift 1 #To read next directory/file name
done
if [ ! -f "" ]                        
then
echo "File  does not exist"
exit 1
fi

for ((i=0; i<; i++))
do
cp "" "$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

将提示移动到 while 循环中可能会有所帮助。循环将为值 re-prompt 直到用户确认它们。确认后,目标代码将被执行,break语句将终止循环。

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