开发者

A "try" shell script

So, the idea is to have a script that tries to run a command, and if the command fails it shows up any warnings/errors. My try:

$ 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

Do you think that this script is ok (wrt portability and functionality)?


Some changes I would make:

  • Use "$@" as Steve Emmerson suggested
  • Don't redirect stdout of tempfile to /dev/null; that's what you're trying to capture in the variable!
  • Consider mktemp; it is more portable.
  • Capture and exit with actual exit code of command, so information is not lost.

E.g., without error checks,

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


I would enclose the $@ in double quotes in the "if" statement in order to preserve word boundaries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜