Sample Header Ad - 728x90

No keyboard output on terminal after running a script using read and whiptail

1 vote
2 answers
1159 views
I've written a bash function that accepts a command as an argument, runs it in the background, and allows the user to kill the command by pressing any key. This part works fine. However, when I pipe it to a whiptail dialog gauge, the whiptail runs as expected, but after it returns, the terminal will no longer display keypresses. I can still run commands, I just don't see what I'm typing printed to the screen. The output is also formatted weirdly, where stdout appears after $. I'm pretty sure the read command is responsible for this behavior, but I don't understand why. Can anyone offer any insight?
#!/bin/bash
function killOnKeypress() {
	local runcommand="${1}"
	local args=(${@:2})

	# Run the command in the background
	"${runcommand}" ${args[@]} &

	# Get the process id of $runcommand
	local pid=$!

	# Monitor $runcommand and listen for keypress in foreground
	while kill -0 "${pid}" >/dev/null 2>&1; do
		# If key pressed, kill $runcommand and return with code 1
		read -sr -n 1 -t 1 && kill "${pid}" && return 1
	done

	# Set $? to return code of $runcommand
	wait $pid

	# Return $runcommand's exit code
	return $?
}

function count100() {
	for ((i = 0; i < 100; i++)); do
		echo $i
		sleep .02
	done
}

killOnKeypress "count100" | whiptail \
	--gauge "Counting to 100" \
	16 56 \
	0
enter image description here
Asked by ridgek (25 rep)
Oct 17, 2021, 10:03 PM
Last activity: Oct 18, 2021, 03:03 PM