I am writing a script to display a menu at the center of the screen for the users to select the options using printf command in bash script.
I am finding the middle column of the screen, and start printing the messages from the middle column. Hence, the output will be displayed at the center.
Below is the code snippet
#!/bin/bash
INSTALLATION_HEADER=" Installater Options "
COLS=$(tput cols)
print_header ()
{
local equal=()
local title="$1"
local mid=$(((${#title}+$COLS)/2))
for (( i=0; $i < ${#title} ; i=$(($i+1)) ))
do
local hypen+="-"
done
printf "%*s\n" $mid "$title"
printf "%*s\n" $mid "$hypen"
echo ""
echo ""
}
print_install_options ()
{
local title=${1}
local mid=$(((${#title}+$COLS)/2))
for (( i=0; $i < ${#title} ; i=$(($i+1)) ))
do
local hypen+="-"
done
printf "%*s\n" $mid "$hypen"
for i in "${install_options[@]}" ;
do
printf "%*s\n" $mid "$i"
done
printf "%*s\n" $mid "$hypen"
}
install_options=("1. Install" "2. Uninstall")
print_header "$INSTALLATION_HEADER"
print_install_options "$INSTALLATION_HEADER"
When I execute the above code, the output produced is
Installater Options
---------------------
---------------------
1. Install
2. Uninstall
---------------------
The expected output should be
Installater Options
---------------------
---------------------
1. Install
2. Uninstall
---------------------
"1. Ïnstall" and "2. Uninstall" are not printing at the middle of the screen. Please help me in resolving it.
Thanks in Advance.
Updated Script:
Thanks to all for anwering my question.
Below is the script which gives the required output.
#!/bin/bash
INSTALLATION_HEADER=" Installater Options "
COLS=$(tput cols)
print_header ()
{
local equal=()
local title="$1"
local mid=$(((${#title}+$COLS)/2))
for (( i=0; $i < ${#title} ; i=$(($i+1)) ))
do
local hypen+="-"
done
printf "%*s\n" $mid "$title"
printf "%*s\n" $mid "$hypen"
echo ""
echo ""
}
print_install_options ()
{
local title=${1}
local length=$(((${#title}+$COLS)))
local mid=$(((${#title}+$COLS)/2))
for (( i=0; $i < ${#title} ; i=$(($i+1)) ))
do
local hypen+="-"
done
printf "%*s\n" $mid "$hypen"
for i in "${install_options[@]}" ;
do
printf "%*s%s" $((${mid}-${#title})) "" "|"
printf "%s" " $i "
printf "%*s\n" $((${#title}-${#i}-5)) "|"
done
printf "%*s\n" $mid "$hypen"
}
install_options=("1. Install" "2. Uninstall")
print_header "$INSTALLATION_HEADER"
print_install_options "$INSTALLATION_HEADER"
Output:
Installater Options
---------------------
---------------------
| 1. Install |
| 2. Uninstall |
---------------------
$COLUMNSinside a script. Resumé:$COLUMNSworks if yousourcethe script.