{
"$type": "site.standard.document",
"canonicalUrl": "https://rednafi.com/misc/dynamic-menu-with-select-in-bash/",
"description": "Build interactive CLI menus with Bash select statement. Create user-friendly command-line tools with option selection and function dispatch.",
"path": "/misc/dynamic-menu-with-select-in-bash/",
"publishedAt": "2023-04-29T00:00:00.000Z",
"site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
"tags": [
"Shell",
"Unix",
"TIL",
"CLI"
],
"textContent": "Whenever I need to whip up a quick command line tool, my go-to is usually Python. Python's\nCLI solutions tend to be more robust than their Shell counterparts. However, dealing with\nits portability can sometimes be a hassle, especially when all you want is to distribute a\nsimple script. That's why while toying around with argparse to create a dynamic menu, I\ndecided to ask ChatGPT if there's a way to achieve the same using native shell scripting.\nDelightfully, it introduced me to the dead-simple select command that I probably should've\nknown about years ago. But I guess better late than never! Here's what I was trying to\naccomplish:\n\n_Print a menu that allows a user to choose an option and then trigger a specific function\nassociated with the chosen option. When you run the script, it should present you with\nsomething similar to this:_\n\nWhenever the user selects an option, the script dispatches an associated function with the\noption. Currently, the associated function just prints You selected option x but it has\nthe freedom to do whatever it wants. The following native Shell script uses select to\nproduce the output above:\n\nThe snippet allows users to make selections from a list of options. It starts by defining an\narray called options which holds the available possibilities. Each option corresponds to a\nspecific function, such as option1, option2, and option3 which can be customized to\nperform specific actions or tasks.\n\nThe script then prompts the user to enter their choice using the select statement. The\nuser's selection is stored in the variable option. Then it uses a case statement to match\nthe selected option and execute the corresponding function. For example, if the user chooses\nOption 1 by typing 1 into the console, the script calls the option1 function and\ndisplays a message confirming the selection. The same applies to Option 2 and Option 3.\nIf the user selects Quit by typing 4, the script breaks out of the loop and terminates.\nMoreover, if the user enters an invalid option, the script displays an error message\nindicating that the option is not recognized and prompts the user to try again.\n\nHere's a little more useful script to run some common Docker commands based on the user's\nselection. The script assumes that Docker engine is installed on the targeted system:",
"title": "Dynamic menu with select statement in Bash"
}