Bash - "읽기" 명령에서 사용자 문자열 입력을 받는 동안 Esc를 누르면 중지한 후 다른 작업을 수행합니다.

Bash - "읽기" 명령에서 사용자 문자열 입력을 받는 동안 Esc를 누르면 중지한 후 다른 작업을 수행합니다.

이 기능을 작동시키려면 어떻게 해야 합니까?

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이 말했습니다.

readEsc 키를 눌러 종료하는 가장 좋은 방법은 다음과 같습니다.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

관련 정보