LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Blogs > konsolebox
User Name
Password

Notices


Rate this Entry

uuidfstab - Convert fstab contents to a format that uses UUID instead of /dev paths.

Posted 09-04-2012 at 09:09 PM by konsolebox
Updated 05-27-2018 at 03:10 PM by konsolebox
Tags bash, fstab, script, uuid

This script helps a user or admin to automatically convert items in fstab so that they would use UUIDs instead.

uuidfstab[.sh]
Code:
#!/bin/bash

function error {
	echo "$1" >&2
	exit 1
}

function show_usage_and_exit {
	error "Usage: $0 <path_to_fstab_file> [<new_fstab_file>]"
}

function process {
	local FSTABFILE=$1 NEWFSTABFILE=$2 LINE DEVICE TEMPFILE ID OUTPUTFILE

	if [[ -n $NEWFSTABFILE ]]; then
		: >> "$NEWFSTABFILE" || error "Unable to create file or write to file: $NEWFSTABFILE"
		OUTPUTFILE=$NEWFSTABFILE
	else
		TEMPFILE=$(exec mktemp)
		[[ -z $TEMPFILE || ! -f $TEMPFILE ]] && error "Unable to create temporary file."
		[[ -w $TEMPFILE ]] || error "Temporary file can't be written into."
		OUTPUTFILE=$TEMPFILE
	fi

	shopt -s extglob

	while read LINE; do
		DEVICE=${LINE%%+([[:space:]])*}
		PRINTED=false
		if [[ $DEVICE == /dev/* ]]; then
			ID=$(exec blkid "$DEVICE" | grep -o "UUID=[^[:space:]]\+" | cut -f 2 -d '"')
			if [[ -n $ID ]]; then
				echo "# $DEVICE = $ID" >&3
				echo "${LINE/$DEVICE/UUID=$ID}" >&3
				PRINTED=true
			fi
		fi
		[[ $PRINTED = false ]] && echo "$LINE" >&3
	done < "$FSTABFILE" 3> "$OUTPUTFILE"

	if [[ -z $NEWFSTABFILE ]]; then
		cat "$TEMPFILE" > "$FSTABFILE" || error "Unable to save modifications to fstab file."
		rm "$TEMPFILE" || echo "Warning: failed to delete temporary file: $TEMPFILE" >&2
	fi

	echo "Operation successful."
}

for A; do
	[[ $A = -h || $A = --help ]] && show_usage_and_exit
done

if [[ $# -ne 1 && $# -ne 2 ]]; then
	echo "Invalid number of arguments." >&2
	show_usage_and_exit
fi

process "$@"
Example output:
Code:
# /dev/sda5 = d964a7a4-2354-4e4a-9d31-5d1983dd3d24
UUID=d964a7a4-2354-4e4a-9d31-5d1983dd3d24		/		ext4		noatime,data=writeback,nobarrier,commit=100,nouser_xattr,noacl		0 1
Get the updated version of this script here.
Posted in Howtos
Views 2118 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 04:21 AM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration