Saturday, May 4, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 2122  / 2 Years ago, fri, october 21, 2022, 8:06:26

I am trying to create a nested case statement in which user input is expected (Y/N). However, the system never waits for the input and always goes to the third option, "Please answer yes or no". Can anyone tell me what I am missing?



Here is the case statement



#!/bin/bash
STATUS=status

find /etc/init.d/* -name '*' -print0 | while IFS= read -r -d '' FILE;
do
if [ "$FILE" != "." -o "$FILE" != ".." ]; then
OUTPUT=$($FILE $STATUS)
case "$OUTPUT" in
*disabled* )
echo "Do you wish to start $FILE ?"
read yn
case $yn in
[yY] | [yY][Ee][Ss] )
$FILE start
;;
[nN] | [n|N][O|o] )
;;
* )
echo "Please answer yes or no.";;
esac
;;
* )
echo "App $FILE is running"
;;
esac
fi
done


Running under Ubuntu 14.04 LTS



Sample output



App /etc/init.d/reboot is running
App /etc/init.d/resolvconf is running
App /etc/init.d/rsync is running
App /etc/init.d/rsyslog is running
App /etc/init.d/samba is running
App /etc/init.d/samba-ad-dc is running
Do you wish to start /etc/init.d/saned ?
Please answer yes or no.

More From » bash

 Answers
6

You're piping find output to the while loop. The inner read command is reading a line from find's output, not from stdin.



You can restructure like this: send the find output to the while loop on a different file descriptor. This leaves stdin free for the inner read.



while IFS= read -u3 -r -d '' FILE; do
if [ "$FILE" != "." -o "$FILE" != ".." ]; then
OUTPUT=$($FILE $STATUS)
case "$OUTPUT" in
*disabled* )
read -p "Do you wish to start $FILE ?" yn
case $yn in
[yY] | [yY][Ee][Ss] ) $FILE start ;;
[nN] | [nN][Oo] ) ;;
* ) echo "Please answer yes or no.";;
esac
;;
* ) echo "App $FILE is running" ;;
esac
fi
done 3< <(find /etc/init.d/* -name '*' -print0)


This uses a process substitution, instead of a pipe, to read from find


[#24428] Sunday, October 23, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rontablis

Total Points: 293
Total Questions: 123
Total Answers: 104

Location: Austria
Member since Mon, Mar 1, 2021
3 Years ago
;