#!/bin/sh tmp="$(mktemp)" test "$(id -u)" != "0" && sudo="sudo" die () { echo "$@" >&2 } # Read one character read_char () { die -n ">" old_stty_cfg=$(stty -g) stty raw dd ibs=1 count=${1:-1} 2> /dev/null stty $old_stty_cfg die "" } # mount the device with $1 as the choice mount () { dev="$(grep "^$1\." "$tmp" | cut -f 2- -d ' ')" test -z "$dev" && exit die "mounting /dev/$dev on /media/$dev" mkdir -p /media/$dev $sudo mount /dev/$dev /media/$dev > /dev/null 2>&1 || return 1 } # eject the device with $1 as the choice eject () { printf "$1" | grep -q "[0-9]" || exit 1 mountpoint="$(sed -n "${1}p" "$tmp" | awk '{print $3}')" test -z "$mountpoint" && exit 1 # Get device for mountpoint with df dev="$(df -P "$mountpoint" | tail -n +2 | head -n 1 | # skip headers awk '{print $1}')" die "ejecting $dev" $sudo eject "$dev" && die "Succesfully ejected." || die "Failed to eject." } # print lsblk, use $1 to print only devices with mountpoints or without pr_lsblk () { clear lsblk -o name,size,type,mountpoint die "───────────────────────────────────" lsblk --ascii -o name,mountpoint | grep '^.-' | while read line do words="$(printf "$line" | wc -w)" test $words -eq ${1:-1} && continue printf "%s\n" "$line" done | cut -f 2- -d "-" | awk '{print NR ". " $0}' | tee "$tmp" >&2 } cleanup () { rm -f "$tmp" } trap cleanup EXIT INT die "m(ount) e(ject) ?" choice="$(read_char)" case $choice in "m") i=2; cmd=mount ;; "e") i=1; cmd=eject ;; *) exit 1 ;; esac pr_lsblk $i choice="$(read_char)" $cmd $choice