Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
bash - How to create a disk/partition menu?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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}'
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!