For循环的双变量扩展

时间:2018-05-21 18:36:41

标签: linux bash shell scripting

我试图找出如何在for循环中定义变量。他们  必须等于预定义变量的值,而for循环变量是这些预定义变量名称的一部分。

示例:

PROCESS1="sshd"    --> 1 will be a for loop variable 'i' value
ALIAS1=SSH
PROCESS2="snmpd"   --> 2 will be a for loop variable 'i' value
ALIAS2=SNMP

#Creating array consisting of n number of processes to feed to the for loop

ARRAY=(1 2)

for i in ${ARRAY[@]]};do
PID$i=`ps -elf | grep -i $PROCESS$i`  -->   this is where I am getting stuck
TCP$i=`netstat -anlp | grep $PID$i
done

我正在尝试创建等于" ps"的值的PID1。命令输出,用grepping作为变量PROCESS1的值。

我甚至试过这个:

for i in ${ARRAY[@]]};do

PROCESS=PROCESS$i
ALIAS=ALIASP$i
PID=PID$i

PID$i=`ps -elf | grep -i $$PROCESS`
TCP$i=`netstat -anlp | grep $$PID

这只是试图为" PROCESS1"而不是sshd。

1 个答案:

答案 0 :(得分:0)

为什么不使用bash数组?:

PROCESS=(sshd snmpd)
for i in $(seq 0 $((${#PROCESS[@]}-1)));do
    PID[$i]=$(pgrep "${PROCESS[$i]}")
    TCP[$i]=$(netstat -anlp | grep ${PID[$i]})
done
echo ${#PID[0]} ${#TCP[0]} ${#PID[1]} ${#TCP[1]}

使用bash关联数组来获得乐趣:

PROCESS=(sshd snmpd)
declare -A PID TCP
for i in ${PROCESS[@]};do
    PID[$i]=$(pgrep "$i")
    TCP[$i]=$(netstat -anlp | grep ${PID[$i]})
done
echo ${#PID[sshd]} ${#TCP[sshd]} ${#PID[snmpd]} ${#TCP[snmpd]}

如果必须:

,请使用declare,使用间接引用获取变量值
PROCESS=(sshd snmpd)
for i in $(seq 0 $((${#PROCESS[@]}-1)));do
    declare PID$i="$(pgrep "${PROCESS[$i]}")"
    ref=PID$i
    declare TCP$i="$(netstat -anlp | grep ${!ref})"
done
echo ${#PID0} ${#TCP0} ${#PID1} ${#TCP1}

永远不要使用eval:

PROCESS=(sshd snmpd)
for i in $(seq 0 $((${#PROCESS[@]}-1)));do
    eval "PID$i=\"$(pgrep "${PROCESS[$i]}")\""
    eval "TCP$i=\"\$(netstat -anlp | grep \$PID$i)\""
done
echo ${#PID0} ${#TCP0} ${#PID1} ${#TCP1}