@kojiro's answer解釋與原來的代碼以及問題(*
必須引述到防止將其解釋作爲腳本內部的默認case
分支,並防止作爲參數傳遞時的路徑名擴展)。
@kojiro還指出,可以代替算術表達式擴張字面算術運算符($((...))
)的使用變量引用。 買者:只能作爲$op
- 與$
前綴! - 不僅僅是op
($
前綴在bash中的算術上下文中是可選的)。
考慮到這一點,這裏有一個簡單的解決方案,也執行操作檢查。 (爲了使其完全健壯,也必須檢查操作數)。
#!/bin/bash
n1=$1 op=$2 n2=$3
# Allow 'x' to be passed as an alias for '*' (multiplication).
[[ "$op" == 'x' ]] && op='*'
# Ensure that the operator is valid.
case $op in
+|-|'*'|/) # note the quoted '*', needed to prevent interpretation as wildcard
;;
*) # proper use of unquoted *: the everything-else branch
echo "Error: Unexpected operator: $op" >&2
exit 1
esac
# Perform the calculation. Note how the operator is provided via variable $op.
# Note how the reference to variable `op` _must_ be `$`-prefixed in this case,
# unlike the other two references.
echo $((n1 $op n2))
你需要''*')'(帶引號),否則通配符匹配_anything_。 –
有些讀者可能會感興趣的是,bash會高興地將操作符解釋爲算術表達式。就是說:'x = +; echo $((1 $ x 2)); #輸出3' – kojiro
@kojiro:方便知道。請注意,它只適用於''' - 前綴變量引用(而前綴在算術上下文中通常是可選的)。 – mklement0