Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multitasking Menu in Shell Script

Multitasking Menu in Shell Script

I have a Shell Script ( test.sh ) to do 4 tasks within a menu. The tasks are to clean terminal history, downloads folder, trash can, or exit. The code I have so far is:

#!/bin/bash

function menu {
clear
echo "[1] Clean Terminal"
echo ""
echo "[2] Clean Downloads"
echo ""
echo "[3] Clean Trash"
echo ""
echo "[x] Exit"
echo ""

read -p "Option > " option

}

function terminal {
    clear
    cd
    cat /dev/null > .bash_history
    echo "Terminal history is now cleared!"
}

function downloads {
     clear
     cd
     rm -r Downloads/*
     echo "Downloads directory is now cleared!"
}

function trash {
     clear
     cd
     rm -rf ~/.local/share/Trash/*
     echo "Trash is now cleared!"
}

function terminate {
     exit
}

end_script=0
while [ "${end_script}" != 1 ];do
    menu
    case ${option} in
    1)
        terminal
    ;;

    2)
        downloads
    ;;

    3)
        trash
    ;;


    x)

        terminate
    ;;

    *)
        clear
        echo "unknown usage!"
    ;;
    esac
done

What the Executed Script looks like:

[1] Clean Terminal

[2] Clean Downloads

[3] Clean Trash

[x] Exit

Option > 

What the Problem is:

The problem I am having, is that this menu is only accepting single input from the user (Only able to put 1 number at a time). What I would like it to be able to do is input multiple inputs and just divide them like this (1, 2) or (1 2 3).

What I've Tried So Far...

I've brainstormed a while about this one. One way I thought of doing this was to create individual functions for all variations of numbers and add the code, but this would be extremely time consuming for larger menus, and it doesn't seem very logical.

like image 347
TazerFace Avatar asked Jun 24 '26 23:06

TazerFace


1 Answers

Try this:

#!/bin/bash

while true; do
  read -p "Option > " options
  for option in ${options//,/ }; do   # replace all , by white spaces
   case ${option} in
    1) echo "function terminal";;
    2) echo "function downloads";;
    3) echo "function trash";;
    x) echo "terminate"; exit;;
    *) echo "unknown usage!";;
    esac
  done
done

Example usage at read's prompt: 5,3, 2 1 x

Output:

unknown usage!
function trash
function downloads
function terminal
terminate
like image 175
Cyrus Avatar answered Jun 28 '26 00:06

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!