【问题标题】:How to Ask User for Confirmation: Shell如何要求用户确认:Shell
【发布时间】:2019-06-21 12:04:43
【问题描述】:

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

【问题讨论】:

  • 我试过你的代码,得到了code.tio: line 8: syntax error near unexpected token `then'
  • echo if [[ $REPLY =~ ^[Yy]$ ]] echo 不应该在那里(它解释了@melpomene 提到的错误:它不再是 if/elif/else 构造,它是一个 echo 命令后跟一个then 不与任何 if 关联)
  • @Aaron .... 我还是有点困惑。我将那个 echo 放在 if 语句之前,以便可以在下一行打印其余的输出。无论如何我都删除了它,尽管用户输入确认,代码仍然运行
  • Err 是的,这是有道理的,只有echo "cloning files...."then 块内,其余的都是无条件执行的。当$REPLY[Yy] 不匹配时,反转条件并使其成为exit,或者将脚本的其余部分放在then

标签: bash shell if-statement confirmation


【解决方案1】:

将提示移动到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

【讨论】:

  • 抱歉,再次打扰,但如果用户键入“N”,则代码会继续提示用户回显“您的文件名是 $source_file,副本数是 $number_of_copies。”有没有办法打破这个循环?
  • 通常是 CTRL+C。如果你在 Mac 上,它可能是别的东西。命令 + 句点/点 (.) ?您还可以将while : 更改为while [[ ! "$REPLY" =~ [Xx] ]];,并将确认提示更改为"Press Y for yes N for no X to exit"。然后,用户可以用“X”或“x”回复该提示以终止程序..
猜你喜欢
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多