0

I'm beginning in Bash and I try to do this, but I can't.

Example:

array=("/dev/sda1" "/dev/sdb1")

for i in "${array[@]";do
    space=$(df -H | grep ${array[1]})
done

or this:

i=0

for i in ("/dev/sda1" "/dev/sdb1")
    space=$(df -h | grep (($i++)))
done

Is this possible?

1 Answer 1

1

You can directly feed the array into df like below and avoid using for-loop like

df -H "${array[@]}"

However, if this is a venture to study the for-loop in bash then you can do the same like below

for i in "${array[@]}"
do
 df -H "$i" 
 # Well, "${array[@]}" expands to everything in array
 # and i takes each value in each turn.
done

And if you wish to access the array using index, then

for ((i = 0; i < ${#array[@]}; i++)) # This is a c-style for loop
do 
  df -H "${array[i]}" # Note the index i is not prefixed with $
done

Edit

To check if the usage is more than, say, 10GB

# We will usage file which we would use to fill the body of mail
# This file will contain the file system usage
# But first make sure the file is empty before every run
cat /dev/null > /tmp/diskusagereport
for i in "${array[@]}"
do
 usage=$(df -H "$i" | awk 'END{sub(/G$/,"",$3);print $3}')
 if [ "${usage:-0}" -gt 10 ]
 then
  echo "Filesystem : ${i} usage : ${usage}GB is greater than 10GB" >> /tmp/diskusagereport
 fi
done
#finally use the `mailx` client like below

mailx -v -r "[email protected]" -s "Disk usage report" \
      -S smtp="smtp.yourserver.org:port" -S smtp-auth=login \
      -S smtp-auth-user="your_auth_user_here" \
      -S smtp-auth-password='your_auth_password' \
                         [email protected] </tmp/diskusagereport
Sign up to request clarification or add additional context in comments.

7 Comments

Might as well round out the exercise with for ((i = 0; i < ${#array[@]}; i++)); do df -H "${array[i]}"; done ... :)
Ok but how did the df result to a variable? The idea is to save the result in a variable to be able to execute an if
@Ceac May I know what are you planning to do with the variable? Often you will need a specific value from df to do some computations based on it.
I need to compare it to run a script and trigger an email
@Ceac : compare what? Are you looking to extract a particular field from df For example check the free space is less than 30% or so?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.