4

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your such a fast and thorough explanation. Now I get it work.
@KyleZeng, ...to explain what artM means -- clicking a checkbox next to an answer that solved your problem will mark your question as resolved.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.