I tried some code from unix.com, modifying it to act as a device selector.
#!/bin/bash
count=0
for device in `fdisk -l | sed -n '/^[/]/p' | awk '{print $1}'`
do
count=$((count 1))
dev[$count]=$device
echo "$count: $device"
done
echo "Select volume (numbers 1-$count):"
read selected_number
selected_device=$dev[$selected_number]
echo "The device you selected is: $selected_device"
for some reason the line selected_device=$dev[$selected_number]
is not working as expected.
I imagine I did some beginner's syntax error.
the output it gives is
1: /dev/nvme0n1p1
2: /dev/nvme0n1p2
3: /dev/nvme0n1p3
4: /dev/nvme0n1p4
5: /dev/nvme0n1p5
6: /dev/nvme0n1p6
7: /dev/nvme0n1p7
8: /dev/mmcblk0p1
Select volume (numbers 1-8):
5
The device you selected is: [5]
while I would expect something like The device you selected is: /dev/nvme0n1p5
(I'm running the script as sudo, btw)
thanks in advance for your help.
CodePudding user response:
Something like this,
#!/usr/bin/env bash
count=0
for device in `fdisk -l | sed -n '/^[/]/p' | awk '{print $1}'`; do
count=$((count 1))
dev[$count]=$device
printf '%s: %s\n' "$count" "$device"
done
read -rp "Select volume (numbers 1-$count): " selected_number
printf 'The device you selected is: %s\n' "${dev[$selected_number]}"
Although I suggest to use a while
read
loop with Process Substitution.
while IFS= read -r device; do
count=$((count 1))
dev[$count]=$device
printf '%s: %s\n' "$count" "$device"
done < <(fdisk -l | sed -n '/^[/]/p' | awk '{print $1}')
Also the sed
and awk
part can be just one awk
fdisk -l | awk '/^[/]/{print $1}'