如何要求用户确认:Shell

时间:2019-06-21 12:04:43

标签: bash shell if-statement confirmation

我是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 $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

1 个答案:

答案 0 :(得分:0)

将提示移到while循环中可能会有所帮助。循环将重新提示输入值,直到用户确认为止。确认后,将执行目标代码,并且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