Bash - 如果按下来自“读取”命令,立即停止并执行其他工作

Bash - 如果按下来自“读取”命令,立即停止并执行其他工作

我怎样才能使该功能发挥作用?

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

相关内容