GRaj
GRaj

Reputation: 31

Better bash script to read two entries of each line of file into two variables

On CentOS linux, I have /etc/fstab that includes following entries:

/dev/dsk/xfsvold00     /mnt/00vol    xfs    defaults   0     2
/dev/dsk/xfsvold01     /mnt/01vol    xfs    defaults   0     2
/dev/dsk/xfsvold02     /mnt/02vol    xfs    defaults   0     2
/dev/dsk/xfsvold03     /mnt/03vol    xfs    defaults   0     2
/dev/dsk/xfsvold04     /mnt/04vol    xfs    defaults   0     2
/dev/dsk/xfsvold05     /mnt/05vol    xfs    defaults   0     2
/dev/dsk/xfsvold06     /mnt/06vol    xfs    defaults   0     2

I am developing a bash script that does filesystem mount. I am trying to get first two entries of each line in /etc/fstab into two variables and use those variables in mounting. For instance, I need:

dev/dsk/xfsvold00     /mnt/00vol
dev/dsk/xfsvold01     /mnt/01vol
dev/dsk/xfsvold02     /mnt/02vol
dev/dsk/xfsvold03     /mnt/03vol

I have the below working prototype code.

mountall() {
  # TODO: find a neat trick to get mntvol and mntpt.
  cat /etc/fstab | grep xfs > /tmp/tmpfstab
  while read mntvol mntpt var3; do
    mount -t xfs $mntvol $mntpt;
    rc=$?
    [ $rc -ne 0 ] && return $rc || echo "mount successful on $mntpt"
  done < /tmp/tmpfstab
  /bin/rm -rf /tmp/tmpfstab
  } 

Is there a better implementation ? Any pointers or tips appreciated. Thanks.

Upvotes: 1

Views: 109

Answers (3)

GRaj
GRaj

Reputation: 31

Based on @tripleee and @Jahid (thank you guys), code with slightly stringent check on filesystem type:

mountall () {
    awk '$3=="xfs"' /etc/fstab |
    while read -r mntvol mntpt var3; do
      mount -t xfs $mntvol $mntpt &&
       echo "mount successful on $mntpt" ||
       echo "mount failed on $mntpt" 
    done
}

Upvotes: 2

Jahid
Jahid

Reputation: 22428

I see several quirks:

  1. There's no need for cat /etc/fstab | grep xfs, grep can take a file argument: grep xfs /etc/fstab
  2. There's no need to put $? into a variable and then comparing the variable with a test command; you could just do: if command;then echo success;else echo failure;fi or command && echo success || echo failure

I would do it like this:

mountall(){
  while read -r mntvol mntpt var3; do
    if mount -t xfs $mntvol $mntpt; then 
      echo "mount successful on $mntpt"
    else
      echo "mount failed on $mntpt"
      return $? # comment this out if you don't want to stop here.
    fi
  done < <(grep xfs /etc/fstab)
}

Upvotes: 1

tripleee
tripleee

Reputation: 189487

You are exiting the loop on the first failure. Fixing the warts along the way, you want

mountall () {
    grep xfs /etc/fstab |
    while read -r mntvol mntpt var3; do
      mount -t xfs $mntvol $mntpt &&
       echo "mount successful on $mntpt"
    done
 }

If the intent is really to abort on the first failure, switch the && echo back to a || return.

Upvotes: 1

Related Questions