Linux A「;试一试;shell脚本
因此,我们的想法是让脚本尝试运行命令,如果命令失败,它会显示任何警告/错误。我的尝试:Linux A「;试一试;shell脚本,linux,shell,portability,Linux,Shell,Portability,因此,我们的想法是让脚本尝试运行命令,如果命令失败,它会显示任何警告/错误。我的尝试: $ cat try.sh #! /bin/sh tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/temp$$ trap 'rm -f $tempfile >/dev/null 2>&1' 0 trap 'exit 2' 1 2 3 15 echo "$@" if ! "$@" >$tempfile 2>&1; t
$ cat try.sh
#! /bin/sh
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/temp$$
trap 'rm -f $tempfile >/dev/null 2>&1' 0
trap 'exit 2' 1 2 3 15
echo "$@"
if ! "$@" >$tempfile 2>&1; then
cat $tempfile;
false;
fi
你认为这个脚本可以吗(wrt可移植性和功能)?为了保留单词边界,我会在“if”语句中用双引号括起$。我会做一些更改:
- 按照Steve Emmerson的建议使用“$@”
- 不要将
的标准输出重定向到tempfile
;这就是您试图在变量中捕获的内容李>/dev/null
- 考虑
;它更便于携带mktemp
- 捕获并使用命令的实际退出代码退出,因此信息不会丢失
tempfile=`mktemp 2>/dev/null || echo /tmp/tempfile$$`
[ -w "$tempfile" ] || { echo "Can't make tempfile" >&2; exit 1; }
"$@" 2> $tempfile
rc=$?
case $rc in
0) ;;
*) cat "$tempfile" >&2 ;;
esac
rm -f "$tempfile"
exit $rc
我个人会用Python重写这个。我很欣赏那些能用shell脚本快速开发出复杂工作程序的人,但我自己不会冒这个风险。让脚本执行命令能让你得到什么,而直接执行命令却不能得到什么?@Steve,这可能是更大脚本的一部分,要在命令没有失败时抑制输出,我的直觉是,这不适用于复杂的带引号的命令。我支持lpthnc关于用Python(或Perl)编写本文的观点。