· 6 years ago · May 19, 2019, 07:16 PM
1#!/bin/bash
2nvm_location="/media/nvm"
3device_node="/dev/mmcblk0"
4partition_number="4"
5partition_node="${device_node}p${partition_number}"
6previous_partition_number=$(($partition_number-1))
7previous_partition_node="${device_node}p${previous_partition_number}"
8
9create_partition () {
10
11# Start by getting the last sector of the previous partition
12last_sector=$(fdisk -l $device_node | awk -v str="$previous_partition_node" '$0~str{print $3}')
13
14# Feed input into fdisk to create the partition
15sed -e 's/\s*\([\+0-9a-zA-Z]*\).*/\1/' << EOF | fdisk ${device_node}
16 o # clear the in memory partition table
17 n # new partition
18 p # primary partition
19 ${partition_number} # partition number
20 $(($last_sector+1)) # Start just after the end of the previous partition
21 # default - extend to the end of the disk
22 w # write the partition table
23 q # and we're done
24EOF
25}
26
27# Exit if the partition is already mounted
28if df -h | grep -q "$nvm_location"; then
29 echo "NVM partition is already mounted"
30 exit 0
31else
32 echo "NVM partition is not mounted"
33fi
34
35# Attempt to mount the NVM partition (it needs to exist in fstab)
36if mount "${nvm_location}"; then
37 echo "Successfully mounted existing NVM"
38 exit 0
39else
40 echo "Unable to mount $nvm_location partition."
41fi
42
43# We couldn't mount the partition location. See if the partition_node exists
44if [ ! -f "$partition_node" ]; then
45 echo "Device node $partition_node does not exist"
46 # Add partition to table
47 create_partition
48 # TODO: zero out the node
49else
50 echo "Device node $partition_node already exists and should have mounted. Something is wrong, likely with the filesystem."
51 exit 1
52fi
53
54# Attempt to mount the NVM partition
55if mount "${nvm_location}"; then
56 echo "Successfully mounted existing NVM"
57 exit 0
58else
59 echo "Unable to mount $nvm_location partition."
60fi
61
62# We couldn't mount the partiton location. We already created the partition, so create the filesystem
63if mkfs.ext4 "$partition_node"; then
64 echo "Successfully made ext4fs"
65else
66 echo "Failed to make ext4fs"
67 # TODO: Exit with failure
68fi
69
70# Try to mount again; return the exit code
71mount "${nvm_location}"