Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

linux - Total count of the array values

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
" "$(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)?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
" "${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[@]}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...