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 

相關內容