0

Multitasking Menu in Shell Script

Let's say 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.

1 Answer 1

1

If I'm understanding your question you want to allow user to enter multiple menu codes at the prompt separated by some delimeter. Then you want to be able to process them one at a time. If so, use space as delimeter and then you can easily convert the input string to an array and iterate over it's contents:

# let's say user enters "a b c" and we store in input_str
input_arr=($input_str)
for cmd in "${input_arr[@]}"; do
  # process command associated with $cmd
done

Putting the codes in an array isn't totally necessary but is convenient as you can access any individual code, determine the total number, etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .