0

How to make a command output list into a menu option list with Bash?

Command: mount | grep /media | awk '{print $3}' lists all mounted USB Storages on my computer.

  • It could be empty or multiple lines.
  • When it is empty, I will echo a message.
  • When it is multiple lines, I want to make this output into a menu option list as:

    1. AAA
    2. BBB
    3. CCC
    4. ...

The difficulty is, the output is not fixed number of lines, so the menu will be unfixed choice.

I am stuck.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
cooleo
  • 1
  • 1
  • 1
    Welcome to Stack Overflow. SO is a question and answer page for professional and enthusiastic programmers. Add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself. – Cyrus May 22 '20 at 11:33
  • 2
    are you aiming only for a LIST, or a MENU, which menu will then have some other purpose, and actually be selectable?? – Ron May 22 '20 at 13:26

4 Answers4

1

Here's something that work:

#!/bin/sh

output=$(mount|grep /media|awk '{print $3}')

if [[ -z $output ]]; then
    # output is empty
    echo "Empty not found"
else
    # output is not empty
    echo $output
fi

Can you provide a preview of your output so I can format it as well

Joe
  • 63
  • 1
  • 9
1

From your description I understand that you like to dynamically create an menu or selection list from a command output given. A possible solution can be something like

#!/bin/bash

# Gather the USB drives into an array
unset DRIVES
while IFS= read -r LINE; do
  DRIVES+=("${LINE}")
done < <(mount -l | grep /dev/sd | awk '{print $3}') # < You may change this for your needs ... since I dont have USB in my VM

# Iterate over an array to create select menu
select USB in "${DRIVES[@]}" "Quit"; do
  case ${USB} in
    /)
      echo "Drive ${USB} selected"
      # Further processing
      ;;
    "Quit")
      echo "Exit"
      break
      ;;
    *)
      echo "Not available"
      ;;
  esac
done

Thanks to

U880D
  • 8,601
  • 6
  • 24
  • 40
1

Sorry for answering a very old thread but it might help someone

#!/bin/bash
select mntvar in $(mount | grep '/media' | awk '{print $3}'); do break;done
0

If you really wanted the list items to be numbered in the #) fashion, you could do something like this.

#!/bin/bash

count=0

for each in $(mount | grep '/media' | awk '{print $3}'); do 
  count=$(( count + 1 ))
  echo "${count}) $each"
done

if [ "$count" -eq 0 ]; then
  echo "No disks found."
fi

The if statement at the end triggers if loop never runs because of zero results.

Chris Gillatt
  • 1,026
  • 8
  • 13