You are not logged in.

#1 2011-11-19 08:06:45

MikeW
Member
Registered: 2011-10-19
Posts: 66

String parsing

I am fairly new to bash so this may not be the best way to do this. I am attempting to improve my backup script. What the script does is checks to see if the external drive is mounted and if so where. smile

Does this make sense or is there a better way to do this?

#!/bin/bash

# Script to determine where a particular device is mounted.

deviceID='ab61c599-e8ca-4578-9ebb-f607de9d3693'

# Parse the mountpoint for the device
mountpoint=`mount | grep $deviceID | awk '{print $3}'`

if [ ! -z $mountpoint ]; then
  echo mounted on $mountpoint
else
  echo not mounted
fi

Offline

#2 2011-11-19 09:10:43

MikeW
Member
Registered: 2011-10-19
Posts: 66

Re: String parsing

Update I think I improved things a bit, this seems to work in all cases now no matter how the drive is mounted.

# Find out where the device is mounted.
deviceID='ab61c599-e8ca-4578-9ebb-f607de9d3693'
device=`blkid | grep $deviceID | awk '{print $1}' | sed 's/\(.*\)./\1/'`
mountpoint=`mount | grep $device | awk '{print $3}'`

echo mountpoint: $mountpoint

if [ ! -z $mountpoint ]; then
  echo Backup device mounted on $mountpoint
else
  # Device not mounted, try to mount it.
  echo not mounted
  if [ ! -z $device ]; then
    mkdir -p /mnt/backup
    mount -t ext3 $device /mnt/backup
    if [ $? -eq 0 ]; then
      echo Backup device mounted, starting backup.
    else
      echo Failed to mount backup device, exiting.
      exit
    fi
  else
    echo Backup device not found, verify that the external drive is plugged in.
  fi
fi

Offline

#3 2011-11-19 13:54:42

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: String parsing

You're overcomplicating things. util-linux tools can do this all this parsing for you.

#!/bin/bash

UUID=ab61c599-e8ca-4578-9ebb-f607de9d3693
device=$(blkid -lt "UUID=$UUID" -o device)

if [[ -z $device ]]; then
  echo "Device not found"
  exit 1
fi

if target=$(findmnt -runo target "UUID=$UUID"); then
  printf 'backup device mounted on %s\n' "$target"
else
  target=/mnt/backup
  [[ -d $target ]] || mkdir -p "$target"
  if mount "$device" "$target"; then
     printf 'backup device mounted on %s\n' "$target"
  else
     echo "failed to mount device"
     exit 1
  fi
fi

Last edited by falconindy (2011-11-19 17:14:40)

Offline

#4 2011-11-20 00:40:26

MikeW
Member
Registered: 2011-10-19
Posts: 66

Re: String parsing

Thanks, I figured I might be. It may be time to do some reading on whats available in util-linux. smile

Offline

Board footer

Powered by FluxBB