我怎樣才能讓這個功能發揮作用?
Esc接受使用者輸入時按下將退出腳本
read -r -p "Enter the filenames: " -a arr
if press Esc; then
read $round
mkdir $round
fi
for filenames in "${arr[@]}"; do
if [[ -e "${filenames} ]]; then
echo "${filenames} file exists (no override)"
else
cp -n ~/Documents/library/normal.cpp "${filenames}"
fi
done
我如何檢測Esc這個腳本中的密鑰?
PS:看了很多資源
https://www.linuxquestions.org/questions/linux-newbie-8/bash-esc-key-in-a-case-statement-759927/
他們使用另一個變數喜歡$key
或read -n1 $key
只是一個字元輸入
但在這兒如果我有一個字串或陣列我該怎麼辦?
答案1
這應該適用於巴什:
#!/bin/bash
# Bind the Escape key to run "escape_function" when pressed.
bind_escape () { bind -x '"\e": escape_function' 2> /dev/null; }
# Unbind the Escape key.
unbind_escape () { bind -r "\e" 2> /dev/null; }
escape_function () {
unbind_escape
echo "escape key pressed"
# command/s to be executed when the Escape key is pressed
exit
}
bind_escape
# Use read -e for this to work.
read -e -r -p "Enter the filenames: " -a arr
unbind_escape
# Commands to be executed when Enter is pressed.
for filename in "${arr[@]}"; do
echo "$filename"
done
答案2
Esc字元是一個特殊字元。
通常,當我想用read
命令截取特殊字元(如 ESC、F1...F12、箭頭...)時,我會使用循環。
#! /bin/bash
declare -r CHAR_LF=$'\n'
declare -r CHAR_ESC=$'\e'
declare -i FLAG_ESC=0
declare RES=
echo -n "Enter the filenames: "
while read -r -N 1 -p "" -d "" CHAR; do
if [[ "${CHAR}" == "${CHAR_ESC}" ]]; then
FLAG_ESC=1
echo
break
elif [[ "${CHAR}" == "${CHAR_LF}" ]]; then
break
else
RES+="${CHAR}"
fi
done
if [[ $FLAG_ESC -eq 1 ]]; then
echo "ESC pressed"
else
echo "Use RES variable with '${RES}' value"
fi