【发布时间】:2020-03-05 17:20:46
【问题描述】:
以下是获取用户输入文件名的简单函数,但由于某种原因,我的输入验证不起作用。
function getname
{
echo "Please enter the name of the file to install: "
read filename
if (($args > 1))
then
echo "You entered to many arguments."
echo $USAGE
exit
fi
}
getname
Bash -x test1 产生这些结果,就好像它没有看到 $args 的任何值:
bash -x test1
+ getname
+ echo 'Please enter the name of the file to install: '
Please enter the name of the file to install:
+ read filename
testfile
+ (( > 1 ))
test1: line 9: ((: > 1: syntax error: operand expected (error token is "> 1")
为什么这不起作用?
谢谢!
【问题讨论】:
-
你在哪里将内容分配给变量 $args?
-
在函数定义之前我有一个 args=$#.. 也许我做错了,$# 会返回命令行参数,但我没有传递任何参数。
-
您的脚本有效。这意味着问题出在您未在此处显示的部分。
-
$#返回 number 个命令行参数,而不是命令行参数。但根据跟踪,args变量未设置为任何值。所以不,您没有args=$#(这会将args设置为一个数字:0、1 等)。绝对不清楚您要实现什么 - 如果用户输入了多个单词,它们将全部存储在 filename 变量中。例如,尝试read f; echo "{$f}"并输入foo bar
标签: linux bash shell scripting redhat