I am facing an issue as not able to pause inside a function and wait user confirmation to continue or exit the script, the background is I am writing a verification function which verify against an input file and I want it pause when encounter a certain value from input, ideally it able to temporary suspend the function and provide user a menu including Continue
or Exit
, only after user select the function will resume the execution or the script terminate.
Create an example to test, some idea get from Press space to continue and How do I prompt for Yes/No/Cancel input in a Linux shell script?, as my test, it not work by just ignore the read
command line which suppose to pause function and wait user input.
test.sh
#!/bin/bash
function pause(){
read -n1 -rsp $'Press any key to continue or Ctrl+C to exit...\n'
}
function wait_user_confirm() {
echo "When encounter number 2 ask user to confirm continue"
while IFS= read -r line; do
if [[ "$line" -eq 2 ]]; then
pause # Not pause the function till user input and ignored by script
else
echo "Skip"
fi
done < "input.txt"
}
wait_user_confirm
input.txt
1
2
3
Test result:
When encounter number 2 ask user to confirm continue
skip
skip
I test that read
command individually (not inside a function, directly as a command line only), it works properly, the issue not because of read
command, its because it not able to pause inside a function of shell script. How can I properly pause the function of shell script and wait for user input by providing a select menu ? Appreciate all the help, thanks