表达式和变量

表达式和变量

我如何运行脚本: ./script.sh 1 \* 2

最终:./script.sh 1 '*' 2

我的脚本是什么样子的:

args="$@" # the first line of the script
result=$(($args))
echo "$args = $result"

是否有效: 是

我想要实现的目标:我想用expr而不是$((...))

就像是:

args="$@" # the first line of the script
result=`expr $args`
echo "$args = $result"

它对于像 之类的输入参数工作得很好,但是对于星号(星号)符号1 + 2来说它不能正常工作(或者更可能的是:) 。expr: syntax error我想知道为什么这不能按预期工作以及我应该如何解决这个问题。

像这样的脚本:expr "$@"确实有效 - 我只是不明白当我分配$@给变量时发生了什么。

答案1

为什么你的脚本不起作用

您的脚本现在执行通配符扩展,以将通配符替换为当前工作目录中的所有文件。如果您将set -x选项添加到脚本顶部,这一点就会很明显。

$ ./expr_script.sh 2 '*' 2
+ args='2 * 2'
++ expr 2 -23.txt add_location_name.py expr_script.sh kusalananda 'Movie A (2014)' 'Movie B (2016)' one.test popup_script.sh somefile2.txt somefile.txt somethings texts three.test turnSignal.v two.test 2
expr: syntax error
+ result=
+ echo '2 * 2 = '
2 * 2 = 

如何修复它

您不需要在算术脚本中扩展文件名,因此可以使用set -f选项禁用全局扩展。

#!/bin/bash
set -f
##set -x
args="$@" # the first line of the script
result=$(expr $args)
echo "$args = $result"

这有效:

$ ./expr_script.sh 2 '*' 2
2 * 2 = 4

相关内容