tech:shell_script_lvm_lsblk_get_vgfree_space_without_root_privileges
Shell script LVM lsblk get vgfree space without root privileges
vg_free.sh
#! /bin/bash # Creative Commons CC0 Public Domain Licence set -euo pipefail IFS=$' \t\n' export LC_ALL=C SCRIPT_NAME="$(basename "$0")" usage() { cat <<-EOF Usage: $SCRIPT_NAME [ VG_NAME ] Usage: $SCRIPT_NAME [ -a|--all ] Usage: $SCRIPT_NAME [ -h|--help ] $SCRIPT_NAME display volume groups free space in MiB for non-root users. $SCRIPT_NAME [ VG_NAME ] Is equivalent : sudo vgs --readonly --noheadings --units=m [ VG_NAME ] -o vgfree $SCRIPT_NAME --all Is equivalent : sudo vgs --readonly --noheadings --units=m -o vgname,vgfree EOF } command_exists() { if ! command -v "$1" >/dev/null 2>&1 ; then echo -e "Missing command : $1\nAborting." >&2 exit 127 fi } calc_sum() { awk '{s+=$1} END {printf "%.0f", s}' "$*" } get_vg_size() { local VG_NAME=$1 lsblk -b -i | grep -B1 -E -e '[|`]-'"${VG_NAME/-/-*}-" | awk '/part|disk|crypt/ { print $4 }' | calc_sum } get_lv_total_size() { local VG_NAME=$1 #lsblk -p -b -o NAME,SIZE -J --nodeps "/dev/${VG_NAME}"/* |jq '.blockdevices[].size |tonumber' lsblk -p -b -n -o SIZE --nodeps "/dev/${VG_NAME}/"* | calc_sum } get_vg_list() { # shellcheck disable=SC2012 ls -1 /dev/mapper/ | awk '/-/{print $1}' | sed -e 's/-[^-]*$//' -e 's/--/-/' | sort -u } get_vgfree() { local VG_NAME=$1 local -i VG_SIZE local -i LV_TOTAL_SIZE VG_SIZE="$(get_vg_size "$VG_NAME")" LV_TOTAL_SIZE="$(get_lv_total_size "$VG_NAME")" echo "$(( ( VG_SIZE - LV_TOTAL_SIZE ) /1024/1024 ))" } check_inputs() { local VG_NAME=$1 if [[ ! -d "/dev/${VG_NAME}" ]] then echo "Volume group $VG_NAME not found" >&2 exit 5 fi } main() { local VG_NAME=${1-} local -i VG_FREE command_exists lsblk if [[ "$NOARGS" -eq 1 ]] then for VG in $(get_vg_list) do VG_FREE="$(get_vgfree "$VG")" printf " %-8s %10.2fm\n" "$VG" "$VG_FREE" done else VG_FREE="$(get_vgfree "$VG_NAME")" echo " ${VG_FREE}.00m" fi } if [[ $# -eq 0 ]] then echo "$SCRIPT_NAME: missing operand" >&2 echo "Try '$SCRIPT_NAME --help' for more information." >&2 exit 1 fi while [ "${1-}" != "" ]; do case $1 in # --debug ) DEBUG=1 # ;; -a | --all ) shift NOARGS=1 main ;; -h | --help ) usage exit 0 ;; --) # End of all options shift break ;; -*) echo "SCRIPT_NAME: invalid option" >&2 echo "Try '$SCRIPT_NAME --help' for more information." >&2 exit 1 ;; *) check_inputs "$1" NOARGS=0 main "$1" ;; esac shift done
Sinon il est toujours possible de s'en sortir avec quelques commandes
lsblk -b -i |grep -B1 vg00 |awk '/part|disk/crypt/ { print $4 }' | awk '{s+=$1} END {printf "%.0f", s}' lsblk -b -i |grep -B1 vg00 |awk '/lvm/ { print $4 }' |awk '{s+=$1} END {printf "%.0f", s}'
tech/shell_script_lvm_lsblk_get_vgfree_space_without_root_privileges.txt · Dernière modification : de Jean-Baptiste
