SORU
15 EYLÜL 2008, PAZARTESİ


Hata BASH işleme

BASH hataları işlemek için favori yöntemi nedir? Web üzerinde buldum BASH hata işleme en iyi örnek http://www.linuxcommand.org William Shotts, Jr tarafından yazıldı.

William Shotts, Jr BASH işleme: hata için aşağıdaki işlevi kullanarak önerir

#!/bin/bash

# A slicker error handling routine

# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run.  You can get this
# value from the first item on the command line ($0).

# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>

PROGNAME=$(basename $0)

function error_exit
{

#   ----------------------------------------------------------------
#   Function for exit due to fatal program error
#   	Accepts 1 argument:
#   		string containing descriptive error message
#   ----------------------------------------------------------------


    echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
    exit 1
}

# Example call of the error_exit function.  Note the inclusion
# of the LINENO environment variable.  It contains the current
# line number.

echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."

BASH komut kullandığınız daha iyi bir hata işleme yordamı var mı?

CEVAP
9 EKİM 2008, PERŞEMBE


Bir tuzak kullanın!

tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  exit "${code}"
}
trap 'error ${LINENO}' ERR

geçici dosya oluşturma zaman ...o zaman,:

temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles =( "$temp_foo" )

ve $temp_foo çıkışta silinecek ve geçerli satır numarası yazdırılır. (set -e aynı şekilde sen-çıkış-hata davranışı though it comes with some caveats) verecektir.

Sen-ebilmek da izin tuzak çağrı error (Bu durumda kullandığı varsayılan çıkış kodu 1 ve hiçbir mesaj veya arama Kendin sağlamak ve açık değerler; örneğin:

error ${LINENO} "the foobar failed" 2

durumu ile çıkılacak 2, ve açık bir mesaj vermek.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • eHow

    eHow

    27 NİSAN 2006
  • Jejoab

    Jejoab

    4 NİSAN 2008
  • Kevin Bruckert

    Kevin Brucke

    30 Aralık 2006