我怎样才能让这个功能发挥作用?
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
最好的解决方案是从文件中读取文件路径或将它们作为参数传递给脚本,例如@terdon 说
read
按 Escape 键退出的最佳方法似乎是:https://superuser.com/questions/1267984/how-to-exit-read-bash-builtin-by-pressing-the-esc-key/1447324#1447324
另一种较差的方法(它无法区分 Esc 和箭头键按下):
#!/usr/bin/env bash
inputString=''
clear() { printf '\033c'; }
ask() {
clear
printf '%s' "Enter the filenames: $inputString"
}
ask
while :; do
read -rN 1 char
case "$char" in
$'\e') # Esc (or arrow) key pressed
clear
exit
;;
$'\n') # Enter key pressed
break
;;
$'\177') # Backspace key pressed
[[ "${#inputString}" -gt 0 ]] &&
inputString="${inputString::-1}"
ask
continue
;;
*)
;;
esac
[[ -n "$char" ]] &&
inputString+="$char"
done
array_fromString() {
local -n array_fromString_a="$1"
local IFS=$'\n'
array_fromString_a=(
$(xargs -n1 <<< "$2")
)
}
files=()
array_fromString files "$inputString"
echo "Entered filenames: "
printf '%s\n' "${files[@]}"
答案2
这是我调整脚本的方法。希望能帮助到你。
这应该适用于巴什:
#!/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 filenames in "${arr[@]}"; do
if [[ -e "${filenames}" ]]; then
echo "${filenames} file exists (no override)"
else
cp -n ~/Documents/library/normal.cpp "${filenames}"
fi
done