Bash
我如何期待’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"
這一切似乎都不起作用。有人可以在正確的方向上輕推我嗎…?:)
PS:我想一旦我跨過第一個障礙,我就需要添加
\r
一個1
…
在
echo -e "? \c"
中,該\c
部分不是列印出來的任何東西,它是命令的指令,在echo
作為參數傳遞的字元串之後不列印換行符¹。所以在期望中,你需要期望字元串"? "
(問號,空格)。由於expect
命令的參數?
是萬用字元的模式,因此您需要按字面解釋問號:expect -ex "? " send "1\r"
¹的其他一些實現
echo
,例如內置的 bash,使用此語法echo -n "?"
。
您快到了。考慮使用
read
內置(來自TDLP:Catching User Input):閱讀範例
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