Bash 使用?用sh脚本

Bash 使用?用sh脚本,bash,shell,tar,Bash,Shell,Tar,当我阅读一些shell脚本时,我遇到了以下代码行 FILENAME=/home/user/test.tar.gz tar -zxvf $FILENAME RES=$?FILENAME if [ $RES -eq 0 ]; then echo "TAR extract success fi 我想知道 变量前面的“?”标记有什么用途(RES=$?FILENAME) 如何检查焦油提取是否成功 默认情况下,函数的退出状态是函数中最后一个命令返回的退出状态。函数执行后,使用标准的$?变量确定函数

当我阅读一些shell脚本时,我遇到了以下代码行

FILENAME=/home/user/test.tar.gz
tar -zxvf $FILENAME
RES=$?FILENAME
if [ $RES -eq 0 ]; then
    echo "TAR extract success
fi
我想知道

  • 变量前面的“?”标记有什么用途(RES=$?FILENAME)
  • 如何检查焦油提取是否成功

  • 默认情况下,函数的退出状态是函数中最后一个命令返回的退出状态。函数执行后,使用标准的
    $?
    变量
    确定函数的退出状态

    #!/bin/bash
    # testing the exit status of a function
    my_function() {
    echo "trying to display a non-existent file"
    ls -l no_file
    }
    echo "calling the function: "
    my_function
    echo "The exit status is: $?"
    $
    $ ./test4
    testing the function:
    trying to display a non-existent file
    ls: badfile: No such file or directory
    The exit status is: 1
    
    要检查tar是否成功执行,请使用

    tar xvf "$tar" || exit 1
    

    默认情况下,函数的退出状态是函数中最后一个命令返回的退出状态。函数执行后,使用标准的
    $?
    变量
    确定函数的退出状态

    #!/bin/bash
    # testing the exit status of a function
    my_function() {
    echo "trying to display a non-existent file"
    ls -l no_file
    }
    echo "calling the function: "
    my_function
    echo "The exit status is: $?"
    $
    $ ./test4
    testing the function:
    trying to display a non-existent file
    ls: badfile: No such file or directory
    The exit status is: 1
    
    要检查tar是否成功执行,请使用

    tar xvf "$tar" || exit 1
    
    在标准(POSIX ish)shell中,
    $?
    是一个。即使是Bash也没有记录其他含义

    在上下文中,如果上一个命令成功,
    $?FILENAME
    可能会扩展到
    0FILENAME
    ,如果失败,可能会扩展到
    1FILENAME

    由于需要进行数值比较(
    -eq
    ),值
    0FILENAME
    可能会转换为
    0
    ,然后比较OK。但是,在我的系统(Mac OS X 10.10.5,Bash 3.2.57)上,尝试:

    if [ 0FILE -eq 0 ]; then echo equal; fi
    
    生成错误
    -bash:[:0预期的文件:整数表达式

    因此,在
    $?
    之后添加
    文件名
    充其量是非正统的(或者令人困惑,甚至最终是错误的)。

    在标准(POSIX ish)shell中,
    $?
    是一个错误。即使是Bash也没有记录其他含义

    在上下文中,如果上一个命令成功,
    $?FILENAME
    可能会扩展到
    0FILENAME
    ,如果失败,可能会扩展到
    1FILENAME

    由于需要进行数值比较(
    -eq
    ),值
    0FILENAME
    可能会转换为
    0
    ,然后比较OK。但是,在我的系统(Mac OS X 10.10.5,Bash 3.2.57)上,尝试:

    if [ 0FILE -eq 0 ]; then echo equal; fi
    
    生成错误
    -bash:[:0预期的文件:整数表达式

    因此,在
    $?
    之后添加
    文件名
    ,充其量也不是正统的做法(或者令人困惑,甚至最终是错误的)