4
\$\begingroup\$

I wrote a small script to manipulate fields of a file based on the input of a user. Is there something I could've done better, or perhaps a better refactor? I do know however that I need a way to validate for empty fields.

view_column() {
 for i in "$file_name"; do
 cat "$i" | awk -v col="1ドル" '{ print $col }'
 done
}
print_menu() {
 menu=( 'First' 'Last' 'Email' 'Exit' )
 for (( i=0; i<${#menu[@]}; i++ )); do
 printf "%2d. %s\n" "$((i+1))" "${menu[$i]}"
 done
}
main() {
 while true; do 
 clear
 print_menu
 read -p 'Enter a choice: ' choice
 if (( "$choice" == 4 )); then
 break
 fi
 view_column "$choice"
 sleep 1.5
 done
}
rolfl
98.1k17 gold badges219 silver badges419 bronze badges
asked Jul 23, 2013 at 14:01
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

That's very elegant looking code. bash has a builtin select statement to present a menu to the user and get a response -- the advantage of select is that the user is locked into it until a valid response is obtained. Plus, it seems that printing the menu and reading the response should be together.

My code below is not as beautiful as yours, but it allows you to localize all knowledge about the file structure into a single line: local fields=(...)

main() {
 local PS3='Enter a choice: '
 local fields=(First Last Email)
 # reverse the fields array: map field names to column numbers
 local -A column
 for (( i=0; i < ${#fields[@]}; i++)); do
 column[${fields[i]}]=$((i+1))
 done
 while true; do
 clear
 select choice in "${fields[@]}" Exit; do
 # invalid response
 [[ -z $choice ]] && continue
 # exit
 [[ $choice = "Exit" ]] && return
 # do something interesting
 view_column "${column[$choice]}"
 sleep 1.5
 break
 done
 done
}
answered Jul 24, 2013 at 19:51
\$\endgroup\$
1
  • \$\begingroup\$ I appreciate the comment, your code looks good as well! I've never tried using PS3 that looks really handy to use for this kind of situation. Could you explain a little bit more what you're doing with: column[${fields[i]}]=$((i+1)) \$\endgroup\$ Commented Jul 24, 2013 at 21:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.