onur
onur

Reputation: 6365

How can I use loop variable in array?

I have a script for writing to disk usage to csv file like this:

#!/bin/bash

disklist=(
/
)
[ -f "disk.conf" ] && disklist=($(<disk.conf))   

datesed=$(date +"%d\/%m\/%Y")

df -P "${disklist[@]}" | sed -ne 's/^.* \([0-9]\+\)% \(.*\)$/'$datesed', \2, \1%/p' >> disk.csv

Output like this:

11/06/2015, /, 18%
11/06/2015, /dev, 1%
11/06/2015, /bin, 5%

But some filesystems sometimes getting read-only. So I need to check and write this. I can use while-do if filesystem read-only or not like this(simple touch tmp file):

#!/bin/bash

while read -r diskpath2;
do 
diskpath=${diskpath2}

touch $diskpath/readonly-check.tmp

if [ ! -f $diskpath/readonly-check.tmp ]; then
readonly="yes"
else
readonly="no"
fi

echo "$diskpath --> $readonly"

rm -rf $diskpath/readonly-check.tmp

done < disk.conf

I need to use that in my array for every filesystems and if read-only, write like this:

11/06/2015, /, 18%(READ-ONLY)
11/06/2015, /dev, 1%(READ-ONLY)
11/06/2015, /bin, 5%

disk.conf:

/
/dev
/bin

How can I do this?

Upvotes: 0

Views: 57

Answers (1)

NeronLeVelu
NeronLeVelu

Reputation: 10039

#!/bin/bash

DateSed="$( date +'%d/%m/%Y' )"

if [ -a disk.conf ]
  then
    cat disk.conf
  else
    # list of default disk (1 by line) to test
    echo "/"
  fi \
 | while read ThisDisk
    do
      # return status of this disk
      echo "${DateSed}, ${ThisDisk}, $( df -P "${ThisDisk}" | sed 's#.*[[:space:]]\([0-9]\{1,\}[%]\)[[:space:]]/.*#\1#;2!d' )$( [ ! -w "${ThisDisk}" ] && echo "(Read-Only)" )"
    done
  • change a bit the script treating each disk one by one in a loop
  • use several $() based on the Disk name for each info
  • assuming that there is no disk name/ mount point that contain AnyNumber%

Upvotes: 1

Related Questions