Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash select loop doesn't work

Tags:

linux

bash

I'm trying to learn bash. In some tutorial, I found select loop. But it doesn't work on either my MAC OS or Linux. My code is like this:

#!/bin/bash
names="Kyle Cartman Stan Quit"
PS3="Select character: "
select name in $names
    do
    echo "name="$name
done

I use ./test.sh to call this program and the result it like this:

1) Kyle
2) Cartman
3) Stan
4) Quit
Select character: Kyle
name=
Select character: Stan
name=
Select character: 

It seems that it can not detect my input. Could anyone help me?

like image 767
Kyle Zeng Avatar asked Sep 19 '25 21:09

Kyle Zeng


1 Answers

The code is fine; its usage is wrong: The allowed entries are 1, 2, 3 or 4, not Kyle, Cartman, Stan, or Quit. (If the user had to type the whole name, what's the point of putting numbers by them?)

The empty string tells you that the user entered something invalid. Observe, by contrast:

1) Kyle
2) Cartman
3) Stan
4) Quit
Select character: 1
name=Kyle
Select character: 3
name=Stan

By the way -- it should be:

# SAFE: quotes everything
echo "name=$name"

...or...

# SAFE: Quotes only the expansion
echo name="$name"

...not...

# BUGGY: Runs expansion unquoted; can remove characters in IFS, expand globs, etc
echo "name="$name

See When Should You Quote? on the Wooledge wiki, or make a habit of running your code through http://shellcheck.net/, which will find issues of this nature.

like image 157
Charles Duffy Avatar answered Sep 21 '25 16:09

Charles Duffy