For trained users, command-line interface of shells, such as BASH, is very convenient for crafting up complex actions that are much more cumbersome to do in GUI. However, some action may require a long line of command that requires looking up documentation to construct. One would find themself using “history” to look up a past invocation for copying to the current line of command. It is thus useful to have a command menu system for these reusable command lines available. choice.sh
is my solution to this need. The content of the script is as follows:
#!/bin/bash
# Read and list lines from "choice.cmd". Allowing user interaction
# through stderr to choose a line and pass it back to stdout so it
# can be "eval"ed by the BASH
mapfile -u 4 -t 4<${BASH_SOURCE[0]%\.sh}.cmd
echo Run command: >&2
for ((i=0;i<${#MAPFILE[@]};i++));do
printf "%4s: %s\n" "$((i+1))" "${MAPFILE[$i]}" >&2
done
printf "Choice: " >&2
read i
re='^[1-9][0-9]*$'
if [[ $i =~ $re ]] && [[ $((i-1)) -lt ${#MAPFILE[@]} ]]; then
echo ${MAPFILE[$((i-1))]}
else
echo "echo Cancelled."
fi
One can place file in, say, ~/lib
, and add an alias, alias c='eval `~/lib/choice.sh`'
to the ~/.bashrc
. The menu system can then be invoked by typing c
, enter
on the command line. It will read all lines from the file choice.cmd
in the same directory as the script, list them to the terminal screen using stderr, allow the user to make a choice, and pass the line to stdout so it will be eval
ed by the shell. Example usage is as follows:
cjj@parakeet:~$ c Run command: 1: eval "$(/home/cjj/opt/miniconda3/bin/conda shell.bash hook)" 2: xrandr --output HDMI-1 --mode 1024x768 --scale 1x1 --pos 0x312 3: xrandr --output HDMI-1 --mode 1024x768 --scale-from 1920x1080 --same-as eDP-1 Choice: 1 (base) cjj@parakeet:~$