【发布时间】: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