我如何期待'echo -e "? \c"'?

我如何期待'echo -e "? \c"'?

我被要求编写一个与另一个脚本交互的脚本 - 但我被困住了。我与之交互的脚本回显以下内容,我需要发回一个“1”。但我还不能完全到达那里......

echo -e "Select option 1"
echo -e "? \c"

到目前为止,我已经尝试过 - 据我所知:

expect "?"
send "1" 

expect "? "
send "1"

expect "? \n"
send "1"

expect "? \c"
send "1"

这一切似乎都不起作用。有人可以给我一个正确的方向吗? :)

\rPS:我想一旦1我迈出了第一个障碍,我就需要添加一个......

答案1

在 中echo -e "? \c",该\c部分不是打印出来的任何内容,它是命令的指令,echo在作为参数传递的字符串之后不打印换行符。所以在expect中,需要期待字符串"? "(问号、空格)。由于命令的参数expect是一个模式,其中?是通配符,因此您需要按字面解释问号:

expect -ex "? "
send "1\r"

¹的一些其他实现echo(例如内置的 bash)使用echo -n "?"此语法。

答案2

你快到了。考虑使用read内置的(来自TDLP:捕获用户输入):

阅读示例

cat leaptest.sh

#!/bin/bash
# This script will test if you have given a leap year or not.

echo "Type the year that you want to check (4 digits), followed by [ENTER]:"

read year

if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ("$year" % 100 !=
"0") )); then
  echo "$year is a leap year."
else
  echo "This is not a leap year."
fi

注意6号线。变量year是由BASH动态创建的,用于保存echo语句的输出。

测试用户输入示例

cat friends.sh

#!/bin/bash

# This is a program that keeps your address book up to date.

friends="/var/tmp/michel/friends"

echo "Hello, "$USER".  This script will register you in Michel's friends database."

echo -n "Enter your name and press [ENTER]: "
read name
echo -n "Enter your gender and press [ENTER]: "
read -n 1 gender
echo

grep -i "$name" "$friends"

if  [ $? == 0 ]; then
  echo "You are already registered, quitting."
  exit 1
elif [ "$gender" == "m" ]; then
  echo "You are added to Michel's friends list."
  exit 1
else
  echo -n "How old are you? "
  read age
  if [ $age -lt 25 ]; then
    echo -n "Which colour of hair do you have? "
    read colour
    echo "$name $age $colour" >> "$friends" 
    echo "You are added to Michel's friends list.  Thank you so much!"
  else
    echo "You are added to Michel's friends list."
    exit 1
  fi
fi

在您的特定情况下,您将替换5号线使用脚本中的选项列表,并从第 17 行开始修改 if 以匹配您作为 传递的选项ANS。如果该选项与 匹配if,则执行您的脚本,如下所示sh myscript.sh --option ANS

相关内容