Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash Shell-为什么内置的随机函数返回1?_Bash_Shell - Fatal编程技术网

Bash Shell-为什么内置的随机函数返回1?

Bash Shell-为什么内置的随机函数返回1?,bash,shell,Bash,Shell,今天,我发现我的shell脚本偶尔会提前退出。检查代码后,我发现这是因为在shell脚本的头部有一个set-e,我使用内置函数RANDOM生成了一个随机数 使用set-e,如果脚本中的任何命令返回非零,脚本将立即退出。因此,我编写了一段测试代码,如下所示: set -u #set -e for (( i=0; i < 100; i++ )) do index=$(expr ${RANDOM} % 16) echo "RANDOM return $? , index is $index"

今天,我发现我的shell脚本偶尔会提前退出。检查代码后,我发现这是因为在shell脚本的头部有一个
set-e
,我使用内置函数
RANDOM
生成了一个随机数

使用
set-e
,如果脚本中的任何命令返回非零,脚本将立即退出。因此,我编写了一段测试代码,如下所示:

set -u
#set -e

for (( i=0; i < 100; i++ ))
do
index=$(expr ${RANDOM} % 16)
echo "RANDOM return $? , index is $index"
done
RANDOM return 0 , index is 2
RANDOM return 0 , index is 10
RANDOM return 1 , index is 0
RANDOM return 0 , index is 9
RANDOM return 0 , index is 5
RANDOM return 0 , index is 9
RANDOM return 0 , index is 4
RANDOM return 0 , index is 6
RANDOM return 0 , index is 2
RANDOM return 0 , index is 4
RANDOM return 0 , index is 14
RANDOM return 0 , index is 6
RANDOM return 0 , index is 2
RANDOM return 1 , index is 0
RANDOM return 0 , index is 1
RANDOM return 0 , index is 8
...(more line)
看到了吗?RANDOM返回1,但它正确地生成了随机数,这就是我的shell脚本提前退出的原因。切换到python的随机数生成代码后,我的脚本恢复正常


为什么
RANDOM
返回1?

$?
是您执行的最后一个命令的状态
$RANDOM
不是命令,因此计算它不会影响
$?
。(
$RANDOM
是一个“shell参数”或变量,在计算时生成一个介于0和32767之间的随机整数。)

您看到的
$?
值是执行命令
expr${RANDOM}%16
的结果

如果计算表达式的结果为null或
0
,则
expr
命令将返回状态
1
,因此只要
$RANDOM%16
为0(时间的6.25%),您将获得状态
1

如果您已经执行了
set-e
,并且希望执行一个可能会失败而不终止shell的命令,那么可以附加类似于
| | true
的内容。由于
|
的前缀用作条件,失败只会使条件为假

index=$(expr ${RANDOM} % 16) || true
echo "Status of expr is $?, index is $index"

不要使用
expr
进行算术运算;使用
index=$($RANDOM%16))
index=$(expr ${RANDOM} % 16) || true
echo "Status of expr is $?, index is $index"