Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't match any option in bash select statement

Tags:

bash

I'm trying to use the bash select statement for a command loop. The variable in the select statement is always blank. Here is a simple script that illustrates the problem:

#!/bin/bash

select term in one two exit
do
  echo you selected $term
  case $term in
    one ) echo one; break;;
    two ) echo two; break;;
    exit ) echo will exit; return;;
  esac
done

Here is what happens when I run this script:

$ ./test.sh 
1) one
2) two
3) exit
#? one
you selected
#? two
you selected
#? exit
you selected
#? ^D

Anyone know what I might be doing wrong? I'm on Mac OS X 10.7.3. /bin/bash --version shows: GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11)

like image 499
Mike Mertsock Avatar asked Oct 24 '25 18:10

Mike Mertsock


2 Answers

The script works if you type in "1" or "2" rather than "one" or "two".

like image 147
jedwards Avatar answered Oct 26 '25 09:10

jedwards


@jedwards gave you the immediate answer. However, if you want to protect yourself from other users having the same error, you could do something like this

select term in first second exit; do
  [[ -z $term ]] && casevar=$REPLY || casevar=$term. # or, shorter, casevar=${term:-$REPLY}
  case $casevar in
    1|first) echo "the first option"; break ;;
    2|second) echo "option no. 2"; break ;;
    3|exit) echo bye; break ;;
  esac
done

Note this from the bash manual:

a line is read from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the select command completes. Any other value read causes name to be set to null. The line read is saved in the variable REPLY.

like image 38
glenn jackman Avatar answered Oct 26 '25 08:10

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!