簡體   English   中英

如何在shell腳本中只讀取單個字符

[英]How to read just a single character in shell script

我想要像 C 中的getche()類似的選項。如何從命令行讀取單個字符輸入?

使用read命令可以嗎?

在 bash 中, read可以做到:

read -n1 ans

read -n1適用於 bash

stty raw模式會阻止 ctrl-c 工作,並且會使您陷入輸入循環而無路可走。 手冊頁還說stty -raw不能保證將您的終端返回到相同的狀態。

因此,基於dtmilano 的答案使用stty -icanon -echo可以避免這些問題。

#/bin/ksh
## /bin/{ksh,sh,zsh,...}

# read_char var
read_char() {
  stty -icanon -echo
  eval "$1=\$(dd bs=1 count=1 2>/dev/null)"
  stty icanon echo
}

read_char char
echo "got $char"

在 ksh 中,您基本上可以執行以下操作:

stty raw
REPLY=$(dd bs=1 count=1 2> /dev/null)
stty -raw
read -n1

從輸入中讀取一個字符

echo "$REPLY"

在屏幕上打印結果

文檔: https : //www.computerhope.com/unix/bash/read.htm

有些人的意思是“從命令行輸入”是一個給命令的參數,而不是從標准輸入讀取……所以請不要射擊我。 但是我也有一個(可能不是最復雜的)STDIN 解決方案!

使用 bash 並將數據保存在變量中時,您可以使用參數擴展

${parameter:offset:length}

當然,您可以在給定的參數( $1$2$3等)上執行該操作

腳本

#!/usr/bin/env bash

testdata1="1234"
testdata2="abcd"

echo ${testdata1:0:1}
echo ${testdata2:0:1}
echo ${1:0:1} # argument #1 from command line

執行

$ ./test.sh foo
1
a
f

從標准輸入讀取

腳本

#!/usr/bin/env bash

echo please type in your message:
read message
echo 1st char: ${message:0:1}

執行

$ ./test.sh 
please type in your message:
Foo
1st char: F

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM