思路: ps -elf查看進程ppid根據ppid賽選pid進程 #!/bin/bash #The script is used to print child processes. #Date 2021-01-16 file=/tmp/pid.txt #定義文本路徑 while : do read -p "please input a pid: " pid if [ -z $pid ];then#判斷是否爲空 echo "The input can not be empty (input q or quit to exit)." continue elif [ $pid == "q" ]||[ $pid == "quit" ];then#退出循環 echo "exit." exit fi ps -elf| awk -v pid2=$pid '$5==pid2 {print $0}'>$file#篩選pid if ! grep -qw "$pid" $file;then#過濾pid echo "The input pid does not exist (input q or quit to exit)." continue fi break done child_pid() { ps -elf|awk -v pid_new=$1 '$5==pid_new {print $4}' >$1.txt #將進程id寫入文本 n=`wc -l $1.txt| awk '{print $1}'` if [ $n -eq 0 ];then echo "There are no subprocess under the pid $1" elif [ $n -ne 0 ];then echo "The pid $1 subprocess according to following:" cat $1.txt fi }#定義篩選函數 child_pid $pid for i in `cat $pid.txt` #for循環將每一個子進程包含的子進程篩選出 do child_pid $i done for i in `cat $pid.txt` #for循環遍歷刪除文本 do [ -f $i.txt ] && rm $i.txt done [ -f $pid.txt ] && rm $pid.txt#刪除文本