读取命令在if语句中不起作用。在ksh

时间:2016-04-19 23:45:38

标签: shell unix ksh

如何仅在特定条件下读取用户输入。以下代码在ksh中不起作用:

if [[ $contract = "$fld1" ]];then
   read position?"Enter the position of Contract number in m-n format,m should be less than n "
fi

代码不会在上述条件下等待用户提示

2 个答案:

答案 0 :(得分:5)

发布的代码在ksh下运行正常。

$ contract=c
$ fld1=c
$ if [[ $contract = "$fld1" ]];then
> read position?"Enter the position of Contract number in m-n format,m should be less than n "                         <
> fi
Enter the position of Contract number in m-n format,m should be less than n 1-2
$ echo $position
1-2

在回答hedgehog的评论时,你可能会使用一个不那么令人困惑的提示:

read position?"Enter the position of Contract number in m-n format, (m should be less than n) : " 

请注意,read variable?prompt语法具体为ksh。在bash下,您将使用read -p prompt variable。可用于大多数基于Bourne语法的shell的可移植方法是printf "%s" "$prompt" ; read variable

答案 1 :(得分:1)

这是您的代码的工作版本:

if [[ $contract = "$fld1" ]];then
echo "Enter the position of Contract number in m-n format,m should be less than n"
read position
fi

如果您希望终端等待用户回复,则必须单独添加回声和读取。 这对你很好。 这是输出:

Enter the position of Contract number in m-n format,m should be less than n
##cursor waiting here for an input##