1

This is my first attempt to write a bash script and I'm unable to read array outside for loop.
What I'm trying to do is.. store name of all files from /MyDir in an array.
Check if there is process running with that name.
Store name of process running and not running into different arrays.
Print both the arrays and elements count in each array, outside for loop.
Below is the code I'm working on.
Please guide.

#!/bin/bash
declare -a dead
declare -a live
cd /usr/local/MyDir/
FILES=*
for f in $FILES
do
  ps -ef | grep $f > /dev/null
  if [ $? -eq 0 ];
then
    live+=( "$f" )
    echo "Process $f is running."
else
   dead+=("$f")
   echo "Process $f is not running."
fi
done

echo "${[#@live]} Processes are running."
echo  "List of Processes live ${live[@]}"
echo "${[#@dead]} Processes are dead."
echo "List of Processes dead ${dead[@]}"
  • need moar quoates! – cas May 20 '16 at 12:36
2

Any element of an array may be referenced using following syntax:

${ArrayName[subscript]}

You can easily find out bash shell array length using following syntax:

${#ArrayName[@]}

Change your code at the bottom to the following:

echo "${#live[@]} Processes are running."
echo  "List of Processes live ${live[@]}"
echo "${#dead[@]} Processes are dead."
echo "List of Processes dead ${dead[@]}"

And get a result like this:

~$ bash 2.sh
Process bin is running.
Process games is running.
Process include is running.
Process lib is running.
Process local is running.
Process locale is running.
Process sbin is running.
Process share is running.
Process src is running.
9 Processes are running.
List of Processes live bin games include lib local locale sbin share src
0 Processes are dead.
List of Processes dead 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.