0

How can i get this feature to work?

Pressing Esc while taking inputs from the user will exit the script

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

How can i detect Esc key in this script?

PS: Saw many resources
https://www.linuxquestions.org/questions/linux-newbie-8/bash-esc-key-in-a-case-statement-759927/
they use another variable like $key or read -n1 $key just one character input

but here what will i do if I've a string or an array?

1
  • 1
    You can issue another read call and ask for confirmation to execute then evaluate the reply(yes/no) in an if statement to either copy the files or do something else.
    – Raffa
    Jul 5, 2022 at 17:28

2 Answers 2

0

This should work in bash:

#!/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
1
  • thanks.. this seems to work.. i'll test and let you know :)
    – Mega Bang
    Jul 6, 2022 at 8:10
0

Esc character is a special character.

Usually, when I want to intercept special character like ESC, F1...F12, arrows..., with read command, I use a loop.

#! /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
3
  • if pressed <space> this script takes it as enter, plz fix
    – Mega Bang
    Jul 6, 2022 at 6:41
  • Sorry, code fixed : read ... -N 1 ... -d "" + test on LF char Jul 6, 2022 at 8:13
  • Your code works fine too but raffa's one works better for my script (mentioned above).
    – Mega Bang
    Jul 6, 2022 at 12:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .