Total count of the array values

一个人想着一个人 提交于 2019-12-13 08:57:22

问题


Here I'm accepting few mount points from the user and using each value to get space available on the host.

./user_input.ksh -string /m01,/m02,/m03

#!/bin/ksh
STR=$2

function showMounts {
  echo "$STR"
  arr=($(tr ',' ' ' <<< "$STR"))
  printf "%s\n" "$(arr[@]}"

for x in "${arr[@]}"
 do
   free_space=`df -h "$x" | grep -v "Avail" | awk '{print $4}'`
   echo "$x": free_space "$free_space"
done

#echo "$total_free_space"
}

Problems:

  1. How can I exit for loop if any of the user input mount not avaialble? currently it only add error in the log.
  2. How to get total_free_space (i.e. sum of free_space)?

回答1:


If you want to keep your code , test this (no ksh here). If you don't care, read Ed Morton's answer.

./user_input.ksh -string /m01,/m02,/m03

#!/bin/ksh
STR=$2

function showMounts {
    echo "$STR"
    arr=($(tr ',' ' ' <<< "$STR"))
    printf "%s\n" "${arr[@]}"

    for x in "${arr[@]}"; do
        free_space=$(df -P "$x" | awk 'NR > 1 && !/Avail/{print $4}')
        echo "$x: free_space $free_space"
        ((total_free_space+=$free_space))
    done

    echo "$((total_free_space/1024/1000))G"
}

showMounts

Caution:

"${arr[@]}"

not

"$(arr[@]}"



回答2:


As I said in your last question, you do not need ANY of that, all you need is a one-liner like:

df -h "${STR//,/ }" | awk '/^ /{print $5, $3; sum+=$3} END{print sum}'

I have to say "like" because you haven't shown us the df -h /m01 /m02 /m03 output yet so I don't know exactly how to parse it.



来源:https://stackoverflow.com/questions/32726429/total-count-of-the-array-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!