Hi All,
I am trying to run a do while for an array. And in the do while, I'm trying to get a user response. Depending on the the answer, I go ahead and do something or I move on to next element in the array.
So far I can read the array, but I can't get the if statement to work. Any suggestions will be greatly appreciated!
#!/bin/bash
set -x
linenum=1
array=
ps -ef | grep myAgent | grep -v grep | awk '{print $8}' | while read line ;
do
echo "$linenum : $line"
set -- $line
echo "$1"
array[$linenum]=$1
echo " Would you like to analyze this instance ${array[$linenum]} (y/n)? "
read response ### this does not work
if [ "$response" = Y ] || [ "$response" = y ] ; then
echo "Analysing"
sleep 10
# do some thing.. code snip ..
fi
linenum=$(( linenum + 1 ))
done
#!/bin/ksh
set -x
linenum=1
array=
ps -ef | grep myAgent | grep -v grep | awk '{print $8}' |&
while read -p line
do
....
Or if you're reading from a file and want to prompt a user for input in the middle of a loop:
#!/bin/ksh
file=read.txt
exec 3< $file
while read -u3 f
do
printf 'Your input? (y/n) '
read answer
if [ "${answer}" = y ] -o [ "${answer}" = Y ]; then
echo "answer->[${answer}] readFile->[${f}]"
fi
done
Thanks for the quick replies. I was able to get the read to work.
But for some reason I was not getting inside the if condition loop. I kept getting this error:
./test_agent.sh: line 15 [: too many arguments
Turns out the if statement cannot handle -o or ||. Strange, but that's a problem for some other day.
My code looks like this now, I thought about awk '/myAgent/{print8}', but I then get an extra line with just awk. So I'll have to do a grep -v awk.
#!/bin/bash
linenum=1
array=
ps -ef | grep myAgent | grep -v grep | awk '{print $8}' | while read -p line ;
# or this:
# ps -ef | grep -v awk | awk '/myAgent/{print $8}' | while read line ;
#
do
echo "$linenum : $line"
set -- $line
echo "$1"
array[$linenum]=$1
echo " Analyze instance echo ${array[$linenum]} (y/n)? "
read answer </dev/tty
if [ "$answer" = Y ] ; then
echo "Analysing"
# do something
fi
linenum=$(( linenum + 1 ))
done