pc70
pc70

Reputation: 701

Bash read command - how to accept control characters

I am using the following to read a bunch of parameters from the user.

read -p "Name`echo $'\n> '`" NAME

All my parameters have default values. I want to provide an option to the user to skip providing values at any point. i.e. user might provide values for first 3 parameters and press Ctrl+s to skip entering values for the rest of them.

How can I trap Ctrl+s?

Upvotes: 0

Views: 1488

Answers (2)

that other guy
that other guy

Reputation: 123410

Ctrl+S is the terminal scroll lock character, and is not immediately available. You have two options:

  • Work with the system, use the system standard key combos, and make life easier for yourself and everyone else.

  • Fight the system, insist on using this key combo, do anything it takes to make it happen, and then live with the consequences.

If you want to work with the system, consider using a blank line and/or Ctrl+D, which is already extensively used to end input. This is easy and robust:

if read -p "Name (or blank for done)"$'\n> ' name && [[ $name ]]
then
  echo "User entered $name"
else
  echo "User is done entering things"
fi

Alternatively, here's a start for fighting the system:

#!/bin/bash
settings=$(stty -g)
echo "Enter name or ctrl+s to stop:"
stty stop undef    # or 'stty raw' to read other control chars

str=""
while IFS= read -r -n 1 c && [[ $c ]]
do
  [[ $c = $'\x13' ]] && echo "Ctrl+S pressed" && break
  str+="$c"
done
echo "Input was $str"
stty "$settings"

This will correctly end when the user hits Ctrl+S on a standard configuration, but since it doesn't work with the system, it needs additional work to support proper line editing and less common configurations.

Upvotes: 3

codeforester
codeforester

Reputation: 42999

Not sure what you mean by trapping. The user can input Ctrl+S by typing Ctrl+V and then Ctrl+S, and your script can then do the check:

if [[ $NAME == '^S' ]]; then
  ...
  # skip asking for more values and continue with default values
fi

Upvotes: 0

Related Questions