退出状态与本地变量分配错误 [英] Exit status wrong with local variable assignment

查看:55
本文介绍了退出状态与本地变量分配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例显示了如何将temp_file制作为与调用mktemp相同的行的local,然后使用$?检索的退出状态始终为零,而不管命令是成功还是失败(使用mktemp_xyz使其始终失败).如果预先将temp_file设置为local,则$?退出状态将与预期的一样.

The example below shows how if temp_file is made local as part of the same line that mktemp is called then the exit status retrieved using $? is always zero, regardless of whether the command succeeded or failed (mktemp_xyz is used so that it always fails). If temp_file is made local in advance then the $? exit status is as expected.

有人可以解释这是怎么回事吗?

Can someone explain what is going on here please?

#!/bin/bash

test_1()
{
    local temp_file=$(mktemp_xyz -q -t "test.tmp.XXXXXX")
    local make_temp_file_ret_val=$?

    echo "temp_file: $temp_file"
    echo "make_temp_file_ret_val: $make_temp_file_ret_val"
}

test_2()
{
    local temp_file=""
    temp_file=$(mktemp_xyz -q -t "test.tmp.XXXXXX")
    local make_temp_file_ret_val=$?

    echo "temp_file: $temp_file"
    echo "make_temp_file_ret_val: $make_temp_file_ret_val"
}

test_1
echo ""
test_2

输出为:

$ ./test 
./test: line 6: mktemp_xyz: command not found
temp_file: 
make_temp_file_ret_val: 0

./test: line 16: mktemp_xyz: command not found
temp_file: 
make_temp_file_ret_val: 127

谢谢.

推荐答案

local本身就是命令,而不仅仅是赋值语句的修饰符.在test1中,您正在记录local命令的退出状态,而不是命令替换中的命令的退出状态.在test2中,您已将local命令从分配中分离到标记为local的变量,因此$?包含了您期望的退出状态.

local is a command itself, not just a modifier to an assignment statement. In test1, you are recording the exit status of the local command, not the command in the command substitution. In test2, you've separated the local command from the assignment to the variable marked as local, so $? contains the exit status you are expecting.

不相关,但在将变量标记为本地变量时无需初始化.效果很好:

Unrelated, but you don't need to initialize a variable when marking it as local. This works just fine:

local temp_file
temp_file=$(mktemp_xyz -q -t "test.tmp.XXXXXX")

temp_file会一直保持未设置状态,直到您实际为其分配值为止,但是名称在实际分配值之后才是本地的.

temp_file remains unset until you actually assign a value to it, but the name is local once you actually do assign a value.

这篇关于退出状态与本地变量分配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆