bash脚本在循环外读取数组

bash脚本在循环外读取数组

这是我第一次尝试编写 bash 脚本,我无法在 for 循环之外读取数组。
我想做的是..将 /MyDir 中的所有文件的名称存储在数组中。
检查是否有使用该名称的进程正在运行。
将正在运行和未运行的进程名称存储到不同的数组中。
在 for 循环之外打印数组和每个数组中的元素计数。
下面是我正在处理的代码。
请指导。

#!/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[@]}"

答案1

可以使用以下语法引用数组的任何元素:

${ArrayName[subscript]}

您可以使用以下语法轻松找出 bash shell 数组长度:

${#ArrayName[@]}

将底部的代码更改为以下内容:

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

并得到这样的结果:

~$ 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 

相关内容