I wrote a bash script for listing python processes, ram usage and PID and status in human readable form with colored lines. But I have some trouble with working time of the script. Because of the repeatedly written ps
commands working time is taking too much time.
SCRPITS=`ps x | grep python | grep -v ".pyc" | grep -v grep | awk '{print $NF}'` prepare_text () { if [[ ${2%.*} -gt ${RAMLIMIT} ]]; then # RED TEXT=`printf "\033[31m%-62s %'10d %2s %5s %6s\n\033[0m" "${1}" "${2}" "KB" "${3}" "${4}"` elif [[ ${2%.*} -gt ${RAMLIMIT}/2 ]]; then # YELLOW TEXT=`printf "\033[33m%-62s %'10d %2s %5s %6s\n\033[0m" "${1}" "${2}" "KB" "${3}" "${4}"` else # GREEN TEXT=`printf "\033[32m%-62s %'10d %2s %5s %6s\n\033[0m" "${1}" "${2}" "KB" "${3}" "${4}"` fi TEXTBODY+=${TEXT} } display () { printf "$SUBJECT\n" printf "%-62s %13s %5s %8s\n" "PROCESS" "RAM USAGE" "PID" "STATUS" printf "===========================================================================================\n" printf "${TEXTBODY}\n" } for SCRIPT in ${SCRPITS} do USAGE=`ps aux | grep ${SCRIPT} | grep -v "grep" | awk '{print $6}'` PID=`ps aux | grep ${SCRIPT} | grep -v "grep" | awk '{print $2}'` STATUS=`ps aux | grep ${SCRIPT} | grep -v "grep" | awk '{print $8}'` prepare_text ${SCRIPT} ${USAGE} ${PID} ${STATUS} done display exit $?
I decided to change that approach and I rearrange all script for shortening work time as below:
OIFS=$IFS #save original IFS='\n' SCRIPTS=`ps aux | grep python | grep -v ".pyc" | grep -v grep | awk '{print $NF,",",$5,",",$2,",",$8}'` IFS=${OIFS} prepare_text () { if [[ $((${2%.*})) -gt ${RAMLIMIT} ]]; then # RED TEXT=`printf "\033[31m%-62s %'10d %2s %5s %6s\n\033[0m" "${1}" "${2}" "KB" "${3}" "${4}"` elif [[ $((${2%.*})) -gt ${RAMLIMIT}/2 ]]; then # YELLOW TEXT=`printf "\033[33m%-62s %'10d %2s %5s %6s\n\033[0m" "${1}" "${2}" "KB" "${3}" "${4}"` else # GREEN TEXT=`printf "\033[32m%-62s %'10d %2s %5s %6s\n\033[0m" "${1}" "${2}" "KB" "${3}" "${4}"` fi TEXTBODY+=${TEXT} } display () { printf "$SUBJECT\n" printf "%-62s %13s %5s %8s\n" "PROCESS" "RAM USAGE" "PID" "STATUS" printf "===========================================================================================\n" OIFS=$IFS IFS="," set ${SCRIPTS} for SCRIPT in ${SCRIPTS} do prepare_text $1 $2 $3 $4 done printf "\n\n" IFS=${OIFS} printf "${TEXTBODY}\n" } display exit $?
Now I can get what information I want from ps
at once but I have some problem with formatting and displaying that information.
I can't figure out how can I get each argument from ${SCRIPTS}
, split them and pass to prepare_text
function.
I guess I misunderstand something.