如何在shell中的string内inputstar *

我怎样才能包括*在一个string?

这是我的代码:

 #!/bin/bash # This is a simple calculator using select statement echo -n 'Insert 1st operand: ' read first echo -n 'Insert 2nd operand: ' read second echo 'Select an operator:' operators="+ - * /" select op in $operators do let "result=${first}${op}${second}" break done echo -e "Result = $result" 

当我运行这个代码时, *会将当前目录中的所有文件列为select选项。 我试图用\*来逃避它,但它不起作用。

应扩大其参数。 但是,然后select扩展其参数。 shell将\*扩展为* ,这没有帮助,因为select然后展开* 。 你需要扩展到\* ,这将是\\*

另外,只要使用:
select op in + - \* /;
要么:
select op in "$operators"

首先,你可以把$运算符加双引号,以确保没有解释。 select显示正确的参数列表BTW代码的结尾不能按预期工作:它显示第一个和第二个操作数,但不是操作符

使用dynamic构build的string遇到困难时,数组经常在shell脚本中帮助数组。

 $ operators=( + - '*' / ) $ PS3="choice? " $ select o in "${operators[@]}"; do echo "$o $REPLY"; done 1) + 2) - 3) * 4) / choice? 1 + 1 choice? 2 - 2 choice? 3 * 3 choice? 4 / 4