Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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 UNIX shell:使用最后返回的退出代码的值递增一个变量_Bash_Shell_Variables_Increment_Return Code - Fatal编程技术网

Bash UNIX shell:使用最后返回的退出代码的值递增一个变量

Bash UNIX shell:使用最后返回的退出代码的值递增一个变量,bash,shell,variables,increment,return-code,Bash,Shell,Variables,Increment,Return Code,假设我有一个计数器,由counter=0 现在我想运行一个命令,并通过返回的退出代码增加计数器的值 在自然语言中,我想做counter=$counter+$? 我正在尝试一些东西,比如counter=$(counter+$(?))但没有成功。在一行中正确的方法是什么?对于bash,我建议: counter=$(($counter + $?)) 这也是可能的: counter=$((counter + $?)) 或: declare-i counter=0#设置整数属性 计数器=计数器+$?

假设我有一个计数器,由
counter=0

现在我想运行一个命令,并通过返回的退出代码增加计数器的值

在自然语言中,我想做
counter=$counter+$?

我正在尝试一些东西,比如
counter=$(counter+$(?))但没有成功。在一行中正确的方法是什么?

对于bash,我建议:

counter=$(($counter + $?))
这也是可能的:

counter=$((counter + $?))
或:

declare-i counter=0#设置整数属性
计数器=计数器+$?
或:

declare-i计数器=0
计数器=+$?
对于bash,我建议:

counter=$(($counter + $?))
这也是可能的:

counter=$((counter + $?))
或:

declare-i counter=0#设置整数属性
计数器=计数器+$?
或:

declare-i计数器=0
计数器=+$?

您可以将
$?
的值分配给中间变量,然后使用算术上下文添加:

$?
设置为22:

$ awk 'BEGIN {exit 22}'
$ rtr=$?
$ counter=1
$ echo $((counter+rtr))
23

您可以将
$?
的值指定给中间变量,然后使用算术上下文添加:

$?
设置为22:

$ awk 'BEGIN {exit 22}'
$ rtr=$?
$ counter=1
$ echo $((counter+rtr))
23
在UNIX中,您可以尝试: 计数器=1; 计数器=
expr$counter+1
; echo$计数器

注意:
expr$counter+1
在“+”的两侧都有空格

在UNIX中,您可以尝试: 计数器=1; 计数器=
expr$counter+1
; echo$计数器


注意:
expr$counter+1
在“+”的两边都有空格

谢谢你的解决方案,但我一直在寻找单行解决方案谢谢你的解决方案,但我一直在寻找单行解决方案我可以建议
((counter+=$?)
作为另一个变体。我可以建议
((counter+=$?)
作为附加变体。