#!/bin/bash # Collection of small bash functions utilized in various scripts. ################################################################################ export PATH=$PATH:/opt/openslx/bin:/opt/openslx/sbin dmstate="/run/openslx/dmsetup.state" readonly dmstate df_dev_only() { df -P "$1" 2>&1 | awk '$1 ~ /^\/dev\// {print $0}' } get_backing_dev() { local _dev="$(df_dev_only "$1" | awk '{print $1}' )" [ -b "$_dev" ] || return 1 echo "$_dev" } get_backing_dev_mp() { local _mp="$(df_dev_only "$1" | awk '{print $6}')" [ -d "$_mp" ] || return 1 echo "$_mp" } # Helper to check whether given directory resides in RAM, either # by being mounted as tmpfs or not mounted at all in which case # we assume the same. Returns 0 if so, 1 if otherwise backed, # 2 when errors occur. is_volatile() { [ -z "$1" ] && return 2 local _dev="$(get_backing_dev "$1")" [ -z "$_dev" ] && return 0 # NOTE: ash does not search/replace when the expression is surrounded by quotes [ "x$_dev" = "x"${_dev//\/dev\/mapper/} ] && return 1 local _mp="$(get_backing_dev_mp "$1")" [ -z "$_mp" ] && return 2 # it is a device mapper device, check if it was setup in dracut's initramfs. if [ -s "$dmstate" ]; then grep -qE "^${_dev}\s+${_mp}\s+type=0" "$dmstate" return $? fi return 2 } get_dm_backing_size() { [ -z "$1" ] && return 1 local _dev="$(get_backing_dev $1)" # NOTE: ash does not search/replace when the expression is surrounded by quotes [ "x$_dev" = "x"${_dev//\/dev\/mapper/} ] && return 1 local _dm_line="$(grep -m1 -E "^${_dev}\s+/\s+type=[^0]" "$dmstate")" [ -z "$_dm_line" ] && return 1 local _dm_dev_size="$(echo "$_dm_line" | grep -Po '(?<=physical_size=|virtual_size=)\w*' )" echo ${_dm_dev_size:--1} } regex_match() { echo "$1" | grep -qE "$2" } get_partitions_by_id () { local ID dev exp target exp= # target for the scan, defaults to /dev to check everything target=/dev if [ -b "$1" ]; then target="$1"'*' shift fi # support commas and pipes to separate identifiers local args=$@ set -- ${args//[,|]/ } while [ $# -gt 0 ]; do ID=$1 shift [ -z "$ID" ] && continue # if single digit, e.g. 7, look for 0x7 and 0x07 #[[ $ID =~ ^[0-9]$ ]] && ID="0?$ID" if regex_match "$ID" "^[0-9]$" ; then ID="0?$ID" fi if regex_match "$ID" "^[0-9]{2}$"; then # if double digit look for MBR types and OpenSLX-ID$ID GPT labels exp="$exp|ID_PART_ENTRY_(NAME=OpenSLX-ID|TYPE=0x)$ID" elif regex_match "$ID" "^(0x[0-9]{2}|[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$"; then # if full MBR type (e.g. 0x44) or UUID look for TYPE exp="$exp|ID_PART_ENTRY_TYPE=$ID" else # something else, look for names of partitions / filesystems exp="$exp|ID_(PART_ENTRY_NAME|FS_LABEL)=$ID" fi done exp=${exp:1} #echo "Partition find is '$exp'" >&2 for dev in $(find $target -type b); do udevadm info --name="$dev" | grep -iqE "($exp)\$" \ && echo "$(blockdev --getsize64 "$dev") $dev" done | sort -n -k1 -r | cut -d' ' -f2 }