formatting the output using printf in bash script -
formatting the output using printf in bash script -
i writing script display menu @ center of screen users select options using printf command in bash script.
i finding middle column of screen, , start printing messages middle column. hence, output displayed @ center.
below code snippet
#!/bin/bash installation_header=" installater options " cols=$(tput cols) print_header () { local equal=() local title="$1" local mid=$(((${#title}+$cols)/2)) (( i=0; $i < ${#title} ; i=$(($i+1)) )) 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)) (( i=0; $i < ${#title} ; i=$(($i+1)) )) local hypen+="-" done printf "%*s\n" $mid "$hypen" in "${install_options[@]}" ; 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 execute above code, output produced
installater options --------------------- --------------------- 1. install 2. uninstall ---------------------
the expected output should
installater options --------------------- --------------------- 1. install 2. uninstall ---------------------
"1. Ïnstall" , "2. uninstall" not printing @ middle of screen. please help me in resolving it.
thanks in advance.
updated script:thanks anwering question.
below script gives required output.
#!/bin/bash installation_header=" installater options " cols=$(tput cols) print_header () { local equal=() local title="$1" local mid=$(((${#title}+$cols)/2)) (( i=0; $i < ${#title} ; i=$(($i+1)) )) 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)) (( i=0; $i < ${#title} ; i=$(($i+1)) )) local hypen+="-" done printf "%*s\n" $mid "$hypen" in "${install_options[@]}" ; 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 | ---------------------
change line 34 to
printf "%-*s%s\n" $((${mid}-${#title})) " " "$i"
result:
installater options --------------------- --------------------- 1. install 2. uninstall ---------------------
bash printf
Comments
Post a Comment