2

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

我试图使这个循环工作,以便如果有人输入 1-3,它会读取数字并将变量 timePeriod 更改为“daily”、“bars10s”或“bars100ms”。当我在运行代码以查看它们是否正常时回显 timeCheck 和 timePeriod 变量时,timeCheck 总是正确返回,但无论 timeCheck 变量读取什么,timePeriod 都会读取“每日”。我对 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
4

3 回答 3

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"
于 2013-05-03T14:02:53.953 回答
2

我看到两个错误:

  1. 您的if子句中需要空格
  2. 您有时使用大写字母,有时不使用

以下是有效的:

#!/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
于 2013-05-03T14:01:34.797 回答
2

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

if [ $TimeCheck == 1 ] ; then

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

if (( $TimeCheck==1 )) ; then

对于算术检查,空格不太重要。

于 2013-05-03T13:55:31.257 回答