用户输入无法在bash中正确读取

时间:2013-05-03 13:52:41

标签: bash

我的数据存放在三个目录中的一个,我想创建一个允许用户轻松访问数据的循环。

我正在尝试使这个循环工作,以便如果有人输入1-3,它会读取数字并将变量timePeriod更改为“daily”,“bars10s”或“bars100ms”。当我在运行代码时回显timeCheck和timePeriod变量以查看它们是否正常时,timeCheck总是返回正确,但timePeriod读取“daily”,无论timeCheck变量读取的是什么。我对bash很新,所以任何帮助都会受到赞赏。

#!/bin/bash

echo 

timePeriod=""
timeCheck=0

read -p "Time Period for fac to run(press 1 for daily, 2 for 10 sec 
intervals, 3 for 100ms intervals): " -e -i "$timeCheck" timeCheck

if [ $TimeCheck==1 ] ; then
    timePeriod="daily"
elif [ $TimeCheck==2 ] ; then
    timePeriod="bars10s"    
elif [ $TimeCheck==3 ] ; then
    timePeriod="bars100ms"
else
    echo "Not Valid Time Period. Please re-try."
fi


echo $timeCheck
echo $timePeriod

3 个答案:

答案 0 :(得分:3)

您可以使用select - 这样的菜单。

PS3="Select what you want>"
select answer in "Daily period" "10 sec period" "100 ms" "exit program"
do
case "$REPLY" in
    1) timePeriod="daily" ; break;;
    2) timePeriod="10s" ; break;;
    3) timePeriod="100ms" ; break;;
    4) exit ;;
esac
done

echo "$timePeriod"

答案 1 :(得分:2)

你需要在条件和布尔运算符周围放置空格:

if [ $TimeCheck == 1 ] ; then

但是,由于它是算术测试,因此可能更好:

if (( $TimeCheck==1 )) ; then
算术检查

空格不太重要。

答案 2 :(得分:2)

我看到两个错误:

  1. 您的if条款中需要空格
  2. 你有时会使用大写字母而不是
  3. 以下是有效的:

    #!/bin/bash
    
    echo
    
    timePeriod=""
    timeCheck=0
    
    read -p "Time Period for fac to run(press 1 for daily, 2 for 10 sec
    intervals, 3 for 100ms intervals): " -e -i "$timeCheck" timeCheck
    
    if [ $timeCheck == 1 ] ; then
        timePeriod="daily"
    elif [ $timeCheck == 2 ] ; then
        timePeriod="bars10s"
    elif [ $timeCheck == 3 ] ; then
        timePeriod="bars100ms"
    else
        echo "Not Valid Time Period. Please re-try."
    fi
    
    echo $timeCheck
    echo $timePeriod