4

I am attaching block volume in OCI to a new or existing instance using a script (below). However, if the volume already has a file system type already assigned I will lose all my data!

Is there a way only to run the command sudo mkfs -t ext4 /dev/oracleoci/oraclevdb only if it's not already formatted?

Is there a way to run line 1 below, only if the attached volume is not already formatted?

sudo mkfs -t ext4 /dev/oracleoci/oraclevdb
sudo mkdir /data
sudo mount /dev/oracleoci/oraclevdd /data
df -h

The issue is every time a new instance is created using an existing volume, I lose all my data. However, I want to keep the behaviour for new instances were attaching a new volume.

So something like...

if condition x
   sudo mkfs -t ext4 /dev/oracleoci/oraclevdb
else
 do nothing

I'm running Oracle Linux 8.

MarkK
  • 968
  • 2
  • 14
  • 30

3 Answers3

1

Just check if you can mount it.

if ! sudo mount /dev/oracleoci/oraclevdd /data; then
     if ! sudo mkfs -t ext4 /dev/oracleoci/oraclevdb; then
          echo "och nooo, formatting fialed"
     fi
     if ! sudo mount /dev/oracleoci/oraclevdd /data; then
          echo "Och nooooo, can't mount after formatting, that's odd"
     fi
fi
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

You can get this info running lsblk like so:

lsblk  -o NAME,FSTYPE

and run a test using some script:

export DEVICE="/dev/oracleoci/oraclevdb"
export FSTYPE="ext4"

if ! lsblk -o NAME,FSTYPE | grep $DEVICE | grep $FSTYPE; then
    sudo mkfs -t $FSTYPE $DEVICE
fi
ofirule
  • 4,233
  • 2
  • 26
  • 40
1

You could use file to check for content of anything:

with option:

-b, --brief
    Do not prepend filenames to output lines (brief mode).
-L, --dereference
    option causes symlinks to be followed, as the like-named option in ls
-s, --special-files
    Specifying the -s option causes file to also read argument files which
    are block or character special files.

Create a script conditionalMkExt4:

#!/bin/bash

if [[ ! -b $1 ]] ;then
    echo "Not a block device: '$1'"
    exit 1
fi
sudo /bin/bash <<eof
    read -r partTyp < <(file -Lsb "$1")
    case \$partTyp in
        data ) 
            mkfs -t ext4 "$1"
            ;;
        * )
            echo "Device '$1' is of type: '\$partTyp'"
            exit 1
            ;;
    esac
    if [[ $2 ]] ;then
        [[ -e $2 ]] || mkdir -p "$2"
        mount "$1" "$2"
    fi
eof

Then

conditionalMkExt4 /dev/oracleoci/oraclevdb /data

If you want to be able to whipe any non ext4 partition:

Juste replace case ... esac by

    case \$partTyp in
        *ext4* ) 
            echo "Device '$1' already formated as ext4"
            exit 1  # Comment this if you want to mount if already formated
            ;;
        * )
            mkfs -t ext4 "$1"
            ;;
    esac
    
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137