Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#26 Le 04/02/2011, à 19:59

FRUiT

Re : [Résolu] Calcul de longueur d'une chaine

Totor a écrit :

Bon
je n'ai pas pu m'empêcher

Mais pourquoi ne suis-je pas étonné ? roll

Et bien j'aurais jamais eu l'idée d'utiliser dd... Je vais étudier de près cette solution (et ton lien) mais j'aurais surement pas trop le temps de poster les résultats avant dimanche soir voire lundi. En tout cas c'est sur le feu, grand merci Totor t'es un as !

Dernière modification par FRUiT (Le 04/02/2011, à 19:59)


Neon Suite by FRUiT (kde4.6) [url]http://[Merci de relire les règles]/yzm7cee[/url]
"Pour la carotte, le lapin est la plus parfaite incarnation du mal" (R. Sheckley)
clean

Hors ligne

#27 Le 07/02/2011, à 08:43

FRUiT

Re : [Résolu] Calcul de longueur d'une chaine

Bon et ben, ça marche plutôt très bien ^^

Je mets en résolu.

Toujours un petit souci lors d'un while read hmm stty s'exécute mal et il faut refaire manuelement un stty icanon echo. Pourtant avec un while seul ou un read seul ça marche bien. Sinon pour l'alias sudo, depuis la version sh ça marche de nouveau.

Ah et ça c'est un bashisme apparemment : $'\n' , pas réussi à le faire fonctionner en sh. Par contre, ceci marche ${*##*\\n} à la condition de ne pas interpréter la string avant, et que ce soit bien '\n' de marqué dans la string (ça marche pas avec \012 par exemple à moins de refaire un test avec derrière).

Au final ça donne(ra) à peu près :

#!/bin/sh

#set -x

getL ()
{
  (
    stty -icanon -echo time 10 min 6 < /dev/tty
    printf "\033[s${*}\033[6n\033[u\033[K" > /dev/tty
    result=$(dd if=/dev/tty bs=20 count=1 2>/dev/null)
    stty "${sset}"
    IFS='[;R'
    set -f  ;  set -- ${result}
    echo $(($3-1))
  )
}

put_formated ()
{
  sset="$(stty -g)"
  : ${COLUMNS:=$(tput cols || printf "80")}
  : ${e:="\033"}         ; n="$(tput sgr0 || printf "%s" "${e}[m")"
  : ${M_BRACKETS:="[]"}  ; r="$(tput bel  || printf "%s" "\007")"
  bl="${M_BRACKETS%?}"   br="${M_BRACKETS#?}"

  if [ ! "^${1#-}" = "^${1}" ]; then while getopts ":abc:dehiL:lnoqry" m; do case ${m} in
      e)   lb="fail"  cl="0;31"                              ;;
      a)   lb=" !! "  cl="0;33"                              ;;
      d)   lb="done"  cl="0;32"                              ;;
      q)   lb=" ?? "  cl="0;32"                              ;;
      h)   lb="help"  cl="1;30"                              ;;
      r)   lb="ring"  cl="1;35"                              ;;
      y|o) lb=" OK "  cl="0;32"                              ;;
      L)   lb="${OPTARG}"                                    ;;
      l)   M_LEFT=1                                          ;;
      n)   : ${lb:="info"} ; b="${bs}$(tput cuu1)\r${e}[K"   ;;
      b)   b="${bs}${r}"                                     ;;
      c)   cl="${OPTARG}"                                    ;;
      *)   lb="info"                                         ;;
      \?)                                                    ;;
    esac ; done ; shift $(($OPTIND-1))
    STR="${1}" lb="${M_LABEL:-${2:-${lb}}}"
    cl="${e}[${M_LABEL_COLOR:-${3:-${cl:-"0;34"}}}m"
    cb="${e}[${M_BRACKETS_COLOR:-${4:-${cb:-"0;0"}}}m"
  else
    STR="${*}"
  fi
  [ "${STR}" ] || read -p "> " -r STR ; [ "${STR}" ] || exit 0
  [ "${lb}" ] && lb="$(printf "%04b" "${lb}")" || { bl= br= ; }
  [ "${M_PREFIX}" ] && STR="${M_PREFIX}${n} ${STR}"
  [ "${STR##*\\n}" = "${STR}" ] || M_LEFT=1

  STR="$(printf "%b" "${STR}" | expand)"
  co=$(($COLUMNS-$(getL "${lb}")-${#bl}-${#br})); lr="${e}[${co}G"
  cc=$(getL "${STR}")

  [ $co -le $(($cc%$COLUMNS)) ] && { M_LEFT=1 STR="${STR}\012" ; } || co=$(($co-$cc-${#bl}))
  [ $COLUMNS -lt $cc ] && M_LEFT=1
  [ "$M_LEFT" ] || STR="${e}[${co}G${STR}"

  STR="${b}${n}${STR}${lr}${n}${cb}${bl}${n}${cl}${lb}${n}${cb}${br}${n}"
  printf "%b\n" "${STR}"
}

put_formated "${@}"


Et ceci fonctionne aussi finalement pas mal (bugge moins mais calcule peut-être moins bien) :

#!/bin/sh

#set -x

put_formated () 
{
  : ${COLUMNS:=$(tput cols || printf "80")}
  : ${e:="\033"}         ; n="$(tput sgr0 || printf "%s" "${e}[m")"
  : ${M_BRACKETS:="[]"}  ; r="$(tput bel  || printf "%s" "\007")"
  bl="${M_BRACKETS%?}"   br="${M_BRACKETS#?}"
  clip="((\\${e}|[[:cntrl:]])[\[\#\(\)][\?\(\)]?[0-9;]+?[ABCDfGHKsum]|[[:cntrl:]])"

  if [ ! "^${1#-}" = "^${1}" ]; then while getopts ":abc:dehiL:lnoqry" m; do case ${m} in
      e)    lb="fail"  cl="0;31"                              ;;
      a)    lb=" !! "  cl="0;33"                              ;;
      d)    lb="done"  cl="0;32"                              ;;
      q)    lb=" ?? "  cl="0;32"                              ;;
      h)    lb="help"  cl="1;30"                              ;;
      r)    lb="ring"  cl="1;35"                              ;;
      y|o)  lb=" OK "  cl="0;32"                              ;;
      L)    lb="${OPTARG}"                                    ;;
      l)    M_LEFT=1                                          ;;
      n)    : ${lb:="info"} ; bs="${bs}$(tput cuu1)\r${e}[K"  ;;
      b)    bs="${bs}${r}"                                    ;;
      c)    cl="${OPTARG}"                                    ;;
      *)    lb="info"                                         ;;
      \?)                                                     ;;
    esac ; done ; shift $(($OPTIND-1))
    STR="${1}"
    lb="${M_LABEL:-${2:-${lb}}}"
    cl="${e}[${M_LABEL_COLOR:-${3:-${cl:-"0;34"}}}m"
    cb="${e}[${M_BRACKETS_COLOR:-${4:-${cb:-"0;0"}}}m"
  else
    STR="${*}"
  fi
  [ "${STR}" ] || read -p "> " -r STR ; [ "${STR}" ] || exit 0
  [ "${lb}" ] && lb="$(printf "%04b" "${lb}" | expand | sed -r "s/${clip}//g")" || { bl= br= ; }
  [ "${M_PREFIX}" ] && STR="${M_PREFIX}${n} ${STR}"
  [ "${STR##*\\n}" = "${STR}" ] || M_LEFT=1

  STR="$(printf "%b" "${STR}" | expand)"
  cc=$(printf "%b" "${STR}" | sed -r "s/${clip}//g" | awk '{print length()}'); : ${cc:=0}
  co=$(($COLUMNS-${#lb}-${#bl}-${#br})); lr="${e}[${co}G"

  [ $co -le $(($cc%$COLUMNS)) ] && { M_LEFT=1 STR="${STR}\012" ; } || co=$(($co-$cc-${#bl}))
  [ $COLUMNS -lt $cc ] && M_LEFT=1
  [ "$M_LEFT" ] || STR="${e}[${co}G${STR}"

  STR="${bs}${n}${STR}${lr}${n}${cb}${bl}${n}${cl}${lb}${n}${cb}${br}${n}"
  printf "%b\n" "${STR}"
}

put_formated "${@}"
#synopsis
putf [OPTION...] [-L LABEL] [STRING [[LABEL] [LABELCOLOR] [BRACKETSCOLOR]]

Encore un grand merci à toi Totor (et à tous les autres aussi) et bravo smile



putf example

Dernière modification par FRUiT (Le 11/02/2011, à 15:35)


Neon Suite by FRUiT (kde4.6) [url]http://[Merci de relire les règles]/yzm7cee[/url]
"Pour la carotte, le lapin est la plus parfaite incarnation du mal" (R. Sheckley)
clean

Hors ligne

#28 Le 07/02/2011, à 09:58

Totor

Re : [Résolu] Calcul de longueur d'une chaine

Salut,

cool wink
ça à l'aire pas mal ton outil de rapport d'exécution wink


-- Lucid Lynx --

Hors ligne

#29 Le 07/02/2011, à 11:35

FRUiT

Re : [Résolu] Calcul de longueur d'une chaine

C'est mon 2ème script d'expérimentation de sh lol.

#!/bin/sh
# System maintenance checks

# Define some arbitrary constants
define_constants ()
{
  PRINT="$(which putf)"
  META=0
  if [ -x "$(which tput)" ] && tput setaf 1 >/dev/null 2>&1; then
    : ${COLUMNS:="$(tput cols)"}
    LCOL=${CHK_L:-"31"}   MCOL=${CHK_M:-"33"}  HCOL=${CHK_H:-"32"}
    TCOL=${CHK_T:-"0;0"}  WCOL=${CHK_W:-"35"}  CO="\033["  CC="m"
    FANCY=yes
  fi
}

# Is there an active connection
connected ()
{
  ping -c 1 www.google.com >/dev/null 2>&1
}

# Is "this" run as root
isroot ()
{
  [ $(id -u) -eq 0 ]
}

# Parse infos to screen
printscr ()
{
  [ "${PRINT}" -a "${FANCY}" ] && {
    M_PREFIX="${1}" ${PRINT} ${POPT:-"-i"} "${2}" "${3}" "${4}" "${5}";
  } || \
  {
    [ "${FANCY}" ] && META=$(($META+6))
    M=$((${COLUMNS:-80}+${#TCOL}*2+${#4}+${#CC}*3+${META}-1))
    printf "%${M}b\n" "$(printf "%b%04b%b" "${CO}${TCOL}${CC}${1} ${2} [${CO}${4}${CC}" "${3}" "${CO}${TCOL}${CC}]")"
    META=0
  }
}

# Do all jobs at once
check_all ()
{
  for f in $(egrep -o '^[[:alnum:]_-]+\s?\(\)' $0); do
    f="${f%[[:space]]*\(\)}"
    [ "${f#check}" != "${f}" -a "${f%all}" = "${f}" ] && ${f}
  done
}

# Ask something to user
prompt()
{
  stty -icanon -echo ; local p="${1}" ; local i
  printscr " " "${p}" "Y/N" "33"
  while :; do case "$(head -c1)" in
    [Yy]* ) stty icanon echo ; return 0      ;;
    [Nn]* ) stty icanon echo ; return 1      ;;
        * ) : ;;
  esac ; done
}

# Probing for necessary tools
probe_tools ()
{
  [ -x "$(which cpufreq-set)" ] || { TOGET="cpufrequtils " ; }
  [ -x "$(which sensors)" ] || { TOGET="${TOGET}lm-sensors " ; }
  [ "${TOGET}" ] && {
    printscr " " "${TOGET% *}" "miss" "31"
    prompt "Some packages are missing, install them ?" && {
      sudo aptitude update > /tmp/aptup 2>&1
      sudo aptitude install ${TOGET% *}
      rm /tmp/aptup
    } || return 0
  }
}

#. Check root
check_root ()
{
  [ ! "$silent" ] && isroot && printscr "Running" "as" "root" "$LCOL" "0"
}

#. Check installed linux version
check_mach ()
{
  [ "$status" -o "$silent" ] && return 0
  [ -x "$(which lsb_release)" ] && os=" $(lsb_release -si) $(lsb_release -sc) $(lsb_release -sr)"
  [ -x "$(which uname)" ] && {
    host="$(uname -n)"
    vers="$(uname -sr)"
    arch="$(uname -m)"
  }
  bits=" $(getconf LONG_BIT)bits"
  printscr "${host}:" "${vers}${bits}${os}" "${arch}" "$HCOL" "0"
  return 0
}

# Uptime check
Deprecated_uptime ()
{
  if [ ! "$status" ]; then
    if [ ! "$silent" ]; then
      if [ "$(uptime | grep min)" ] && [  ! "$(uptime | grep day)" ]; then
        upt="$(uptime | awk -F '( |,)' '{print $4" "$5}')"
      elif [ ! "$(uptime | grep min)" ] && [ ! "$(uptime | grep day)" ]; then
        upt="$(uptime | awk '{sub(":", " h ", $3); sub(",", " min", $3); print $3}')"
      elif [ ! "$(uptime | grep min)" ] && [ "$(uptime | grep day)" ]; then
        upt="$(uptime | awk '{sub(":", " h ", $5); sub(",", " min", $5); print $3" "$4" "$5}')"
      elif [ "$(uptime | grep min)" ] && [ "$(uptime | grep day)" ]; then
        upt="$(uptime | awk '{print $3" "$4" "$5" "$6}')"
      fi
      printscr "Uptime:" "${upt%,}" "time" "$HCOL" "0"
    fi
  fi
  return 0
}

#. Uptime check
check_uptime ()
{
  [ "$status" -o "$silent" ] && return 0
  S=$(awk -F. '{print $1}' /proc/uptime)
  d=$(($S/86400))      ; [ $d -ne 0 ] && { [ $d -eq 1 ] && u="$d day, " ||  u="$d days, " ; }
  h=$(($S%86400/3600)) ; [ $h -ne 0 ] && u="$u$h h "
  m=$(($S%3600/60))    ; [ $m -ne 0 ] && { [ $m -le 9 ] && m="0$m" ; u="$u$m min " ; }
  s=$(($S%60))         ; [ $s -ne 0 ] && { [ $s -le 9 ] && s="0$s" ; u="$u$s sec"  ; }
  printscr "Uptime:" "${u%[[:space:]]}" "time" "$HCOL" "0" ;
  return 0
}

#. Check for available updates
check_apt ()
{
  [ -x /usr/lib/update-notifier/apt-check ] || return 0
  [ "$status" -o "$silent" ] || { printscr "Looking up" "for updates" "wait" "$WCOL" && printf "%b" "\033[1A" ; }
  pkill apt-check >/dev/null 2>&1 ; sleep .2
  connected && isroot && aptitude update > /tmp/aptitude.$$ 2>&1
  /usr/lib/update-notifier/apt-check --human-readable 2>/dev/null | while read line; do
    UPNUM=${line%%[[:space:]]*}
    case $UPNUM in
      0) COL=$HCOL ;;
      *) COL=$LCOL ; touch /tmp/updates-available ;;
    esac
    if [ ! "$status" ]; then
      [ ! "$silent" -o $UPNUM -gt 0 ] && line=${line#[0-9]*[[:space:]]} && \
      printscr "APT:" "${line%.}" "$UPNUM" "$COL" "0"
    fi
  done
  if [ "$status" ]; then
    [ -f "/tmp/updates-available" ] && exit 0 || exit 1
  fi
  rm /tmp/updates-available /tmp/aptitude.$$ >/dev/null 2>&1
  return 0
}

# Check for available updates
dep_apt ()
{
  l=0
  [ -x /usr/lib/update-notifier/apt-check ] || return 0
  [ "$status" -o "$silent" ] || { printscr "Looking up" "for updates" "wait" "$WCOL" && printf "%b" "\033[1A" ; }
  pkill apt-check >/dev/null 2>&1 ; sleep .2
  connected && isroot && aptitude update > /tmp/aptitude.$$ 2>&1
  /usr/lib/update-notifier/apt-check --human-readable 2>/dev/null | while read line; do
    UPNUM=${line%%[[:space:]]*}
    case $UPNUM in
      0) COL=$HCOL ;;
      *) COL=$LCOL ; touch /tmp/updates-available ;;
    esac
    if [ ! "$status" ]; then
      [ ! "$silent" -o $UPNUM -gt 0 ] && line=${line#[0-9]*[[:space:]]} && {
        [ $l -eq 0 ] && upd=${line%.} || sec=${line%.}
      }
    fi
    l=$(($l+1))
  done
  if [ "$status" ]; then
    [ -f "/tmp/updates-available" ] && exit 0 || exit 1
  fi
  rm /tmp/updates-available /tmp/aptitude.$$ >/dev/null 2>&1
  printscr "APT:" "$sec" "$UPNUM" "$COL"
  return 0
}

#. Check for required restart
check_restart ()
{
  if [ -f /var/run/reboot-required ]; then
    [ "$status" ] && exit 0 || \
    printscr " " "$(sed -r 's/[\ ]?[\*]+[\ ]?//g' "/var/run/reboot-required")" "boot" "$LCOL" "0" ;
  elif [ ! "$silent" ]; then
    [ "$status" ] && exit 1 || \
    printscr " " "No maintenance restart needed" "boot" "$HCOL" "0"
  fi
  return 0
}

# Check for required filesystem check
deprecated_fs ()
{
  ftype=$(\df -T | awk '/\/$/ {print $2}')
  if [ -f /forcefsck ]; then
    [ "$status" ] && exit 0 || \
    printscr " " "Filesystem check sheduled on next boot" "$ftype" "$LCOL" "0"
  else
    if [ "$status" ]; then
      exit 1
    else
#      if [ -u "$(which tune2fs)" -o $(id -u) -eq 0 ]; then
      if [ -u "$(which tune2fs)" -o isroot ]; then
        remmounts=$(($(tune2fs -l $(\df | awk '/\/$/ {print $1}') | awk '/Maximum mount count/ {print $4}')\
                    -$(tune2fs -l $(\df | awk '/\/$/ {print $1}') | awk '/Mount count/ {print $3}')))
        case $remmounts in
              0) fstate="Filesystem check sheduled on next boot" remmounts="$ftype" COL=$LCOL ;;
          [1-2]) fstate="Filesystem check sheduled shortly" COL=$LCOL ;;
          [3-5]) fstate="Filesystem check sheduled shortly" COL=$MCOL ;;
              *) fstate="Remaining mounts before next filesystem check" COL=$HCOL ;;
        esac
      else
        fstate="No filesystem check sheduled" remmounts="$ftype" COL=$HCOL
      fi
      [ ! "$silent" ] || [ $remmounts -lt 4 2>/dev/null ] && \
      printscr " " "${fstate}" "$remmounts" "$COL" "0"
    fi
  fi
  return 0
}

#. Check for next required filesystem check
check_fs ()
{
  ftype=$(\df -T | awk '/\/$/ {print $2}')
  remmounts="$ftype"
  [ -f /forcefsck ] && {
    [ "$status" ] && exit 0 || {
      COL=$LCOL
      fstate="Filesystem check sheduled on next boot"
    }
  } || \
  {
    [ "$status" ] && exit 1 || {
      [ -u "$(which tune2fs)" ] || isroot && {
        remmounts=$(($(tune2fs -l $(\df | awk '/\/$/ {print $1}') | awk '/Maximum mount count/ {print $4}')-$(tune2fs -l $(\df | awk '/\/$/ {print $1}') | awk '/Mount count/ {print $3}')))
        case $remmounts in
              0) fstate="Filesystem check sheduled on next boot"  COL=$LCOL  ;;
          [1-2]) fstate="Filesystem check sheduled shortly"  COL=$LCOL  ;;
          [3-5]) fstate="Filesystem check sheduled shortly"  COL=$MCOL  ;;
              *) fstate="Remaining mounts before next filesystem check"  COL=$HCOL  ;;
        esac ;
      } || fstate="No filesystem check sheduled"  COL=$HCOL
    }
  }
  [ ! "$silent" ] || [ $remmounts -lt 4 2>/dev/null ] || [ -f /forcefsck ] && \
  printscr " " "${fstate}" "$remmounts" "$COL" "0"
  return 0
}

#. Output the amount of used space on main drive
check_space ()
{
  low=60  top=75
  hdd=$(\df -h | awk '/\/$/ {sub("%", ""); print $(NF-1)}')
    if [ $hdd -lt $low ]; then COL=$HCOL;
  elif [ $hdd -lt $top ]; then COL=$MCOL;
  else COL=$LCOL; fi
  [ "$status" ] && exit $hdd || {
    [ ! "$silent" -o $hdd -gt $low ] && \
    printscr "DF: $(\df -h | awk '/\/$/ {print $1}'):" "usage" "${hdd}%" "$COL" "0"
  }
}

#. Check for processor temperature
check_temp ()
{
  for tz in /proc/acpi/thermal_zone/*; do
    [ -e "$tz" ] || return 0
    temp=$(awk '{print $(NF-1)}' "${tz}/temperature")
    unit=$(awk '{print $NF}' "${tz}/temperature")
    crit=$(awk '/critical/ {print $(NF-1)}' "${tz}/trip_points")
    low=$(($crit-20))  top=$(($crit-10))
      if [ $temp -lt $low ]; then COL=$HCOL;
    elif [ $temp -lt $top ]; then COL=$MCOL;
    else COL=$LCOL; fi
    [ "$status" ] && exit ${temp} || {
      [ ! "$silent" -o ${temp} -gt $low ] && {
        META=1
        printscr "${tz##*/}:" "temperature (crit. +${crit}°${unit})" "${temp}${unit}" "$COL" "0"
      }
    }
  done
  return 0
}

#. Check battery state and level
check_bat ()
{
  low=10  mid=45  top=60  max=100  numbat=0
  for batname in /proc/acpi/battery/*; do
    [ -e "$batname" ] || return 0
    BATV=$(awk '/remaining/ {print $3}' "${batname}/state")
    BATM=$(awk '/last full/ {print $4}' "${batname}/info")
    BATSTATE=$(($BATSTATE+($BATV*$max/$BATM)))
    [ $numbat -ne 0 ] && BATPOWER="${BATPOWER}, "
    BATPOWER="${BATPOWER}${numbat}: $(awk '/charging state/ {print $3}' "${batname}/state")"
    numbat=$(($numbat+1))
  done
  BATSTATE=$(($BATSTATE/$numbat))
    if [ $BATSTATE -lt $mid ]; then COL=$LCOL;
  elif [ $BATSTATE -lt $top ]; then COL=$MCOL;
  else COL=$HCOL; fi
  if [ "$status" ]; then
    [ $BATSTATE -eq $max ] && exit 0 || exit ${BATSTATE}
  else
    [ "$(which acpi)" ] && [ "$(acpi -b | grep remaining)" ] && BATPOWER="${BATPOWER} ($(acpi -b | awk '{print $(NF-1)" "$NF}'))"
    [ ! "$silent" -o $BATSTATE -lt $mid ] && \
    printscr "BAT($numbat):" "${BATPOWER}" "${BATSTATE}%" "$COL"
  fi
  return 0
}

#. Check cpu model name and manufacturer
check_cpuname ()
{
  COL=$HCOL
  [ "$status" -o "$silent" ] && return 0
  cpus=$(awk '/processor/ {n++} END{print n}' /proc/cpuinfo)
  model="$(awk -F': ' '/vendor_id/ {printf $NF" "} /model name/ {printf $NF; exit}' /proc/cpuinfo | tr --squeeze-repeats ' ')"
  printscr "CPU:" "${model}" "$cpus" "$COL" "0" ;
  return 0
}

#. CPU policy and average frequency check
check_cpu ()
{
  COL=$HCOL
  [ "$status" -o "$silent" ] && return 0
  for freq in $(awk -F'[. ]' '/MHz/ {print $(NF-1)}' /proc/cpuinfo); do
    num=$(($num+1))
    tot=$(($tot+$freq))
  done
  [ -x "$(which cpufreq-info)" ] && {
    P="$(($(cpufreq-info -f)*100/$(cpufreq-info -l | awk '{print $2}')))%"
    G="policy: $(awk '/[[:alpha:]]/' /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null) ($(($tot/$num)) MHz)"  ;
  } || \
  {
    P=$(($tot/$num))
    G="MHz"
  }
  printscr "CPU($num):" "${G}" "${P}" "$COL" "0" ;
  return 0
}

# Use lm-sensors to get fans RPM
deprecated_fan ()
{
  [ -x "$(which sensors)" ] || return 0
  COL=$HCOL
  sensors | awk '/fan/' | while read line; do
    f="$(printf "%s" "$line" | awk -F: '{print $1}')"
    r="$(printf "%s" "$line" | awk '{print $2}')"
    u="$(printf "%s" "$line" | awk '{print $3}')"
    printscr "${f}:" "${u}" "${r}" "$COL"
  done
}

#. Use lm-sensors to get fans RPM
check_fan ()
{
  [ "$status" -o "$silent" ] && return 0
  for fan in $(find /sys -type f -name "*fan*" 2>/dev/null | awk '/hwmon/'); do
    [ -f ${fan} -a -f ${fan%/*}/name ] && {
      DRV="sys"
      N="$(\cat ${fan%/*}/name) "
      R=$(awk '/[0-9]/' ${fan})
      printscr "${N}${fan##*/}:" "RPM" "${R}" "$HCOL"
    }
  done
}

#. Check how many displays are connected
check_display ()
{
  [ "$status" -o "$silent" ] && return 0
  [ -d /tmp/.X11-unix ] && {
    dnum=$(\ls /tmp/.X11-unix | wc -l)
    [ -z $DISPLAY ] || this=" (current ${DISPLAY})"
    printscr "Displays" "connected${this}" "${dnum}" "$HCOL"
  }
}

#. Check network device infos
check_net ()
{
  [ "$silent" ] || [ "$status" ] || ! connected && return 0
  oldrx=0  rx=0
  for rx in $(netstat -i | awk '!/pan|lo|Table|Iface/ {print $4}'); do
    [ $rx -gt $oldrx ] && device=$(netstat -i | awk "/${rx}/" | awk '{print $1}')
    oldrx=${rx}
  done
  [ "$device" ] && {
    mac=$(ifconfig $device | sed -n -e '/^.*HWaddr \([:[:xdigit:]]*\).*/{s//\1/;y/ABCDEF/abcdef/;p;q;}')
    lip=$(ifconfig $device | perl -nle'/dr:(\S+)/ && print $1')
    pip="$(curl ifconfig.me 2>/dev/null)|"
    [ "$(ifconfig $device | awk '/adr inet6/')" ] && ipv="ipv6" || ipv="ipv4"
    printscr "Connected:" "${device} (${mac}) ip ${pip}${lip}" "${ipv}" "$HCOL"
  }
}

#. Free memory snapshot
check_mem ()
{
  warn=12  crit=5
  fm="$(awk 'NR==1 {T=$(NF-1)} ; NR==2 {F=$(NF-1)} END {printf "%i", (F/T*100)}' /proc/meminfo)"
  case $fm in
        [0-$crit]) COL=$LCOL  ;;
    [$crit-$warn]) COL=$MCOL  ;;
                *) COL=$HCOL  ;;
  esac
  [ "$status" ] && { [ $fm -le $crit ] && exit 1 || exit 0 ; }
  [ ! "$silent" -o $fm -le $crit ] && printscr "Free" "memory" "${fm}%" "$COL"
}

# Call one or all of the check functions
define_constants
[ ! "$1" ] && check_all || while [ "$1" ]; do
  case $1 in
    -t) probe_tools && exit 0                              ;;
    -s) silent=1 ; [ ! "$2" ] && { check_all; break; }     ;;
    -d) [ "$2" ] && { status=1 ; check_$2 ; } || exit 255  ;;
     *) check_$1  ;;
  esac
  shift
done && exit 0

Dernière modification par FRUiT (Le 07/02/2011, à 11:36)


Neon Suite by FRUiT (kde4.6) [url]http://[Merci de relire les règles]/yzm7cee[/url]
"Pour la carotte, le lapin est la plus parfaite incarnation du mal" (R. Sheckley)
clean

Hors ligne

#30 Le 07/02/2011, à 16:48

Totor

Re : [Résolu] Calcul de longueur d'une chaine

A mais je pensais que c'était ton script d'analyse des erreurs !
juste une petite remarque (je n'ai pas regardé en détail) :

check_uptime ()
{
  [ "$status" -o "$silent" ] && return 0
  S=$(awk -F. '{print $1}' /proc/uptime)
  u="$(date +'%j day(s) %H h %M min %S sec' -d "@${S}")"
  printscr "Uptime:" "${u%[[:space:]]}" "time" "$HCOL" "0" ;
  return 0
}

mais bon, c'est un autre formatage wink

Dernière modification par Totor (Le 07/02/2011, à 16:48)


-- Lucid Lynx --

Hors ligne

#31 Le 07/02/2011, à 17:11

FRUiT

Re : [Résolu] Calcul de longueur d'une chaine

Arf je savais bien que c'était possible avec date. Oui je dois enfoncer quelques portes ouvertes dans ce script mais bon voyons le verre à motié rempli : je sais maintenant convertir un temps secondes en temps jours-heures-minutes-secondes lol ^^ Ca doit surement pas être la seule énormerie. En tout cas si tu en vois d'autres ça m'intéresse.

Sinon pour les erreurs c'est pas très développé (sur le screenshot les erreurs ne sont pas redirigées (DOREDIR étant une variable dont je commente la définition ou pas suivant mon humeur pour rediriger ou pas les erreurs dans putf)). Pour le moment j'ai ça dans mon prompt_command, qui évoluera ensuite (c'est juste une ébauche) :

PROMPT_COMMAND='
  ENUM=$? CARG=$- ; LCMD="$(history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g")"
  history -a ; history -r
  if [ $ENUM -ne 0 ]; then
    # StdErr redirection part
    if [ "$DOREDIR" ] && [ $(id -u) -ne 0 ]; then
      EMSG=$( sh -n -c -l "${LCMD} 2>&1 >/dev/null" )
      [ "$EMSG" ] && [ "$LCMD" ] && case "$ENUM" in
        1|127) ${SEND:-"sendf"} -e "\033[33m$EMSG"  ;;
        *)     ${SEND:-"sendf"} -e "\033[31m$EMSG"  ;;
      esac
    fi
    M_PREFIX="$(cut -d" " -f1 <<< "${LCMD#sudo[[:space:]]*}"):" ${SEND:-"sendf"} -e "error" "$ENUM"
  else
    [ -w "${GHIST}" ] || own "${GHIST}" ; echo "${LCMD}" >> "${GHIST}"
  fi
  [ "${PROMPT_TYPE,,}" == "-s" ] && printf "%b" "\033[s\033[f\033[1;37;40m\033[K\033[f [ $(date "+%H:%M") | ${#DIRSTACK[@]} | $(\pwd) | $ENUM | $CARG ]\033[u"
  unset ENUM EMSG
  [ "$DOREDIR" ] && [ $(id -u) -ne 0 ] && exec 2>&4
'

(Ou alors j'ai mal saisi de quoi tu parles)

Dernière modification par FRUiT (Le 07/02/2011, à 17:24)


Neon Suite by FRUiT (kde4.6) [url]http://[Merci de relire les règles]/yzm7cee[/url]
"Pour la carotte, le lapin est la plus parfaite incarnation du mal" (R. Sheckley)
clean

Hors ligne