用于 ?在 sh 脚本中
use of ? in sh script
当我浏览一些 shell 脚本时,我遇到了以下代码行
FILENAME=/home/user/test.tar.gz
tar -zxvf $FILENAME
RES=$?FILENAME
if [ $RES -eq 0 ]; then
echo "TAR extract success
fi
我想知道
- '?'有什么用?标记在变量前面(RES=$?FILENAME).
- 如何查看tar是否提取成功
通过default
,一个函数的exit status
是函数中最后一个命令返回的退出状态。函数执行后,你使用标准的$?
变量来determine
函数的退出状态:
#!/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 中,$?
是一个 special parameter. Even Bash's parameter expansion 没有记录替代含义。
在上下文中,如果上一个命令成功,$?FILENAME
可能会扩展为 0FILENAME
,如果失败,可能会扩展为 1FILENAME
。
由于请求了数字比较 (-eq
),值 0FILENAME
可能会转换为 0
,然后比较确定。但是,在我的系统上(Mac OS X 10.10.5,Bash 3.2.57)尝试:
if [ 0FILE -eq 0 ]; then echo equal; fi
产生错误 -bash: [: 0FILE: integer expression expected
。
因此,在 $?
之后添加 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).
- 如何查看tar是否提取成功
通过default
,一个函数的exit status
是函数中最后一个命令返回的退出状态。函数执行后,你使用标准的$?
变量来determine
函数的退出状态:
#!/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 中,$?
是一个 special parameter. Even Bash's parameter expansion 没有记录替代含义。
在上下文中,如果上一个命令成功,$?FILENAME
可能会扩展为 0FILENAME
,如果失败,可能会扩展为 1FILENAME
。
由于请求了数字比较 (-eq
),值 0FILENAME
可能会转换为 0
,然后比较确定。但是,在我的系统上(Mac OS X 10.10.5,Bash 3.2.57)尝试:
if [ 0FILE -eq 0 ]; then echo equal; fi
产生错误 -bash: [: 0FILE: integer expression expected
。
因此,在 $?
之后添加 FILENAME
充其量是非正统的(或者令人困惑,甚至最终是错误的)。