spirit posteets tagged bash  [ Profile ]

Sort by: Date / Title /

  1. 1 month ago
    1. # :h Remove a trailing file name component, leaving only the head.
    2. # :t Remove all leading file name components, leaving the tail.
    3. # :r Remove a trailing suffix of the form .xxx, leaving the basename.
    4. # :e Remove all but the trailing suffix.
    5.  
    6. ls /usr/local/share/doc/3dm/3DM_help.htm
    7. cd !$:h           # Enleve le nom de fichier, récupère uniquement le répertoire du dernier argument de la commande précédente
    8. cat !-2$:t       # Ne garde que le nom de fichier du dernier argument de l'avant dernière commande (2eme de la fin)
  2. 1 month ago
    Expansion des accolades
    1. cp filename{,-old}        # cp filename filename-old
    2. cp filename{-old,}        # cp filename-old filename
    3. cp filename{-v1,-v2}    # cp filename-v1 filename-v2
  3. 1 month ago and saved by 1 other
    Ce petit script permet d'émuler une barre de progression et le pourcentage associé. La barre s'adapte automatiquement à la largeur du terminal. On passe en argument les commandes à lancer.
    1. #!/bin/sh
    2.  
    3. # ex :
    4. # ~$ test.sh "command1" "command2"
    5. # [||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||] 100.00%
    6.  
    7. barre_progression ()
    8. {
    9.         nb_iterations=$1
    10.         liste_length=$2
    11.         pourcent=`echo "scale=2;($nb_iterations * 100) / $liste_length" | bc`
    12.         pourcent=`printf "% 3.2f" "$pourcent"`
    13.        
    14.         chaine="$pourcent"
    15.         nb_etoiles=`echo "scale=0;$chaine / $diviseur_barre" | bc`
    16.         etoiles=""
    17.         while test $nb_etoiles -gt 0
    18.         do
    19.                 etoiles="${caractere_barre}${etoiles}"
    20.                 nb_etoiles=`echo "$nb_etoiles - 1" | bc`
    21.         done
    22.         etoiles=`printf "[%-${largeur_barre}s]" "$etoiles"`
    23.         pourcentage=`printf "%7s" "$chaine"`
    24.         #echo "\r${etoiles}${pourcentage}%\r\c"
    25.         printf "%b%b%b" "\r${etoiles}" "${pourcentage}" "%\r\c"
    26. }
    27.  
    28. # INITIALISATION DE LA BARRE DE PROGRESSION
    29. init_progress_bar ()
    30. {
    31.         # caractere qui sera affiche dans la barre de progression
    32.         caractere_barre="|"
    33.        
    34.         # detection de l'OS
    35.         os=`uname -s | tr [a-z] [A-Z]`
    36.        
    37.         # recuperation de la largeur en caracteres du terminal
    38.         if test "$os" = "LINUX"
    39.         then
    40.                 largeur_ecran=`stty -a | grep columns | cut -d ' ' -f7 | tr -d ';'`
    41.         elif test "$os" = "SUNOS"
    42.         then
    43.                 largeur_ecran=`stty | grep columns | cut -d ' ' -f6 | tr -d ';'`
    44.         else
    45.                 echo "Systeme d'exploitation incompatible, programme stoppe"
    46.                 exit 1
    47.         fi
    48.        
    49.         # calcul de la largeur optimale de la barre de progression
    50.         largeur_barre=`echo "$largeur_ecran - 7 - 2 - 1" | bc`
    51.         diviseur_barre=`echo "scale=2;100 / $largeur_barre" | bc`
    52.        
    53.         # protection des variables
    54.         readonly largeur_ecran largeur_barre diviseur_barre caractere_barre
    55. }
    56.  
    57. # gestion de la langue de l'environnement
    58. LC_NUMERIC=C
    59.  
    60. init_progress_bar
    61.  
    62. liste_length=$#
    63. nb_iterations=0
    64. if test $liste_length -gt 0
    65. then
    66.         for i in "$@"
    67.         do
    68.                 nb_iterations=`echo "$nb_iterations + 1" | bc`
    69.                 $i 2>&1 >/dev/null
    70.                 barre_progression "$nb_iterations" "$liste_length"
    71.                 # sleep 1
    72.         done
    73. fi
    74.  
    75. echo " "
  4. sponsorised links
  5. 1 month ago
    Lire continuellement un fichier de log et en cas de détection d'une chaine, exécuter une liste de commande
    1. #!/bin/sh
    2. tail -fn0 /var/log/file.log | while read line ; do
    3.         echo "$line" | grep "pattern"
    4.         if [ $? = 0 ]
    5.         then
    6.                 # Actions
    7.                 echo "Yeah: $line"
    8.         fi
    9. done
  6. 1 month ago
    # onlogdo: a hack to handle a common problem: when a certain message shows up in the log file, an action should be performed. (credits to Ben Wong)
    1. #!/bin/bash
    2.  
    3. # Author: Ben Wong <ben@wongs.net>
    4. # Created on: <2001-08-08 11:56:03 hackerb9>
    5. # Time-stamp: <2002-11-20 14:13:11 bbb>
    6.  
    7. # onlogdo: a hack to handle a common problem: when a certain message
    8. # shows up in the log file, an action should be performed. E.g.: when
    9. # a PC-card network device is inserted, it should be ifconfig'd or
    10. # perhaps dhclient should be run. This program can do that in a fairly
    11. # reasonable way.
    12.  
    13.  
    14.  
    15. ### FIRST, THE HELPER FUNCTIONS ###
    16.  
    17. function showmanpage () {
    18.     cat <<'EOF'
    19. NAME
    20.  
    21.    onlogdo - monitor a log file and execute commands based on patterns
    22.  
    23.  
    24. SYNOPSIS
    25.  
    26.    onlogdo <logfile> <pattern> <command> [ <pattern> <command> ... ]
    27.  
    28.      logfile: a file that gets appended to (e.g., /var/log/messages),
    29.      pattern: a string (can use bash's extended pathname globbing syntax),
    30.      command: the command to run when the previous pattern is seen.
    31.  
    32.  
    33. DESCRIPTION
    34.  
    35.     Onlogdo is a hack to handle a common problem: when a certain
    36.     message shows up in a log file, an action should be performed.
    37.     E.g.: when a PC-card network device is inserted, it should be
    38.     ifconfig'd or perhaps dhclient should be run. This program can do
    39.     that in a fairly reasonable way.
    40.  
    41.     Onlogdo continuously reads lines as they are appended to a log
    42.     file. When a line matches a given pattern, the command associated
    43.     with that pattern is run in the background. The patterns
    44.     recognized are standard pathname globbing (*, ?, []) plus bash's
    45.     extended pattern matching (extglob) syntax (see bash(1)).
    46.  
    47.     The log file is reopened properly, if the log file being read is
    48.     rotated. Also, since it blocks when waiting for new lines, onlogdo
    49.     takes up almost no CPU time.
    50.  
    51.  
    52. PATTERN MATCHING SYNTAX
    53.  
    54.     Don't worry about learning the pattern matching the first time you
    55.     read this manual; you'll rarely need it, unless you're anal about
    56.     being as succinct as possible. (Like the author).
    57.  
    58.     The following is an excerpt from bash's man page; see bash(1) for
    59.     full details. In the following description, a pattern-list is a
    60.     list of one or more patterns separated by a |. Composite patterns
    61.     may be formed using one or more of the following sub-patterns:
    62.  
    63.        *      Matches any string, including the null string.
    64.  
    65.        ?      Matches any single character.
    66.  
    67.        [...]  Matches any one of the enclosed characters. A pair of
    68.               characters separated by a hyphen denotes a range
    69.               expression. If the first character following the [ is a
    70.               ! or a ^ then any character not enclosed is matched.
    71.  
    72.       ?(pattern-list)
    73.              Matches zero or one occurrence of the  given patterns
    74.       *(pattern-list)
    75.              Matches  zero  or  more  occurrences  of the given patterns
    76.       +(pattern-list)
    77.              Matches one or more occurrences of the given patterns
    78.       @(pattern-list)
    79.              Matches exactly one of the given patterns
    80.       !(pattern-list)
    81.              Matches  anything  except  one  of the given patterns
    82.  
    83.  
    84. EXAMPLES
    85.  
    86.     Pipelines are okay:
    87.       onlogdo /var/log/messages '*' 'sleep 5; echo olleH | rev'
    88.  
    89.     Wildcards match filenames as usual in a command:
    90.       onlogdo /var/log/messages 'Segfault' 'rm /*.core'
    91.  
    92.     Multiple pattern and command pairs are allowed:
    93.       onlogdo /var/log/messages \
    94.             'ep0 at pcmcia' '/etc/rc.d/dhclient start' \
    95.             'ep0 detached'  '/etc/rc.d/dhclient stop\
    96.             'wi0 at pcmcia' '/etc/rc.d/dhclient start' \
    97.             'wi0 detached'  '/etc/rc.d/dhclient stop'
    98.  
    99.     Bash's extended pathname globbing to do the same as above:
    100.       onlogdo /var/log/messages \
    101.             '@(ep|wi)[0-9] at pcmcia' '/etc/rc.d/dhclient start' \
    102.             '@(ep|wi)[0-9] detached'  '/etc/rc.d/dhclient stop'
    103.  
    104.     A useful example for NetBSD/hpcmips:
    105.       onlogdo /var/log/messages 'hpcapm: resume' 'sleep 1; xrefresh'
    106.  
    107.     Under NetBSD/hpcmips-1.5.1, the X server screen is overwritten by the
    108.     console on an APM resume. I put the last "onlogdo" example in my
    109.     system xinitrc, so xrefresh will be run automatically. (The sleep
    110.     is there to wait for the console to finish junking up the screen).
    111.  
    112.  
    113. SEE ALSO
    114.  
    115.     tail(1), bash(1)
    116.  
    117. BUGS
    118.  
    119.     If this had been written in Perl it would have used "normal"
    120.     regexp syntax instead of pathname expansion. Bash's extensions
    121.     make the patterns as powerful as regexps, but more recondite.
    122.  
    123.     There is no (documented) way for a command to refer to specifics
    124.     in the line that matched. E.g., if the pattern was "@(ep|wi)0",
    125.     the command wouldn't know if the line contained ep0 or wi0.
    126.  
    127.     The author has spent way too much time perfecting a kludge. No
    128.     matter what you're using onlogdo for, there's probably a more
    129.     "correct" way to do it. On the other hand, onlogdo is widely
    130.     applicable and easy to use, so at least you won't be wasting much
    131.     time while doing it the "wrong" way.
    132.  
    133.     There should be a real man page.
    134.  
    135.  
    136. AUTHOR
    137.  
    138.     Ben Wong <Benjamin.Wong@cc.gatech.edu>
    139.  
    140.  
    141. HISTORY
    142.  
    143.     Onlogdo started life as a one line kludge to work around a bug in
    144.     the interaction between APM and the X server in NetBSD-1.5/hpcmips
    145.     in September of 2001.
    146.  
    147. EOF
    148. }
    149.  
    150.  
    151.  
    152.  
    153.  
    154. ### USAGE AND ARGUMENT SANITY CHECKING ###
    155.  
    156. if [[ $# -lt 3 ]]; then
    157.     showmanpage
    158.     exit 1
    159. fi
    160.  
    161. # Emacs's syntax highlighting doesn't handle single ticks (') properly.
    162.  
    163.  
    164.  
    165. # Check if -v (verbose) flag was given.
    166. if [[ "$1" == "-v" ]]; then
    167.     ifverbose=echo            # Echo commands verbosely, if -v.
    168.     shift
    169. else
    170.     ifverbose=:   # Usually just run a no-op.
    171. fi
    172.  
    173.  
    174. # Make sure the log file is readable.
    175. if [[ ! -r "$1" ]]; then
    176.     echo "onlogdo: \"$1\" is not readable" >&2
    177.     exit 1
    178. fi
    179. if [[ -d "$1" ]]; then
    180.     echo "onlogdo: \"$1\" is a directory" >&2
    181.     exit 1
    182. fi
    183.  
    184.  
    185.  
    186.  
    187.  
    188.  
    189. ### SIGNAL HANDLING AND EXIT CLEANUP ###
    190.  
    191. # Run cleanup function when shell exits.
    192. trap cleanup EXIT
    193.  
    194.  
    195. cleanup () {
    196.     echo "onlogdo: cleaning up..." >&2
    197.     if [[ "$TAILPID" ]]; then
    198.         kill $TAILPID      # Kill the bg tail process.
    199.     fi
    200.     rm -f "$PIPE"              # Delete the named pipe.
    201.     rmdir "$PIPEDIR"
    202.     return 0
    203. }
    204.  
    205.  
    206.  
    207.  
    208. ### MAIN ROUTINE STARTS HERE ###
    209.  
    210. # Don't expand wildcards in pattern arguments as filenames.
    211. set -o noglob
    212.  
    213. # Use bash's extended pattern matching operators
    214. shopt -s extglob
    215.  
    216. # Create a pipe to read the log file a line at a time;
    217. # Use mktemp for security.
    218.  
    219. PIPEDIR=$(mktemp -d /tmp/onlogdo.XXXXXX)
    220. PIPE="$PIPEDIR/$(echo $1 | sed 's#^/##; s#/#.#g')"      # var.log.messages
    221. rm -f $PIPE
    222. mknod $PIPE p
    223. tail -Fn0 $1 >$PIPE &      # FSF tail: "tail --retry -fn0"
    224. TAILPID=$!
    225. exec 5< $PIPE
    226.  
    227. # Copy the positional paramaters in to a variable that can be indexed.
    228. params=("$0" "$@")
    229.  
    230.  
    231. # Repeatedly read from the pipe, process each line.
    232. while :; do
    233.     while read REPLY <&5; do
    234.  
    235.         $ifverbose -e "\nline: \"$REPLY\""
    236.         for ((i=2; i<$#; i+=2)); do
    237.             pattern=${params[$i]}
    238.             command=${params[$((i+1))]}
    239.             $ifverbose "pattern: \"$pattern\""
    240.             if [[ -z "${REPLY##*$pattern*}" ]]; then
    241.                 $ifverbose "*MATCHED*"
    242.                 $ifverbose "command: \"$command\""
    243.                 set +o noglob   # Allow pathname matching in commands
    244.                 eval $command &
    245.                 set -o noglob   # No pathname expansion for patterns
    246.             fi
    247.         done
    248.     done
    249.  
    250.     # We get here whenever the pipe first blocks (returns EOF)
    251.     sleep 1               # Don't loop too quickly
    252. done
    253.  
    254.  
    255. ### MAIN ROUTINE ENDS HERE ###
    256.  
    257.  
    258. # Note: if we ever get here, the cleanup() function will be called
    259. # automatically since we're trapping on signal 0.
  7. 5 months ago and saved by 1 other
    Cette commande va effectuer le status sur tous les fichiers contenus dans $liste_file_to_update, ne récupère que les lignes commençant par M (fichiers modifiés), supprime les 9 premiers caractères (pour supprimer les caractères de statut affichés par svn status) et retire les espaces et caractères numériques restant au début de la ligne.
    1. svn status -u $liste_file_to_update | egrep '^M' | cut -c 9- | sed "s/[1-9 ][1-9 ]*\//\//g"
  8. 5 months ago
    1. trap "/usr/bin/mycmd; exit 255" SIGINT SIGTERM
  9. 8 months ago and saved by 1 other
    1. #Pour changer les permissions récursivement sur les dossiers sans toucher aux autres fichiers :
    2.  
    3. chmod u-w $(ls -l -R | sed -n '/^d/p' | awk '{print $9 }')
    4.  
    5. #va enlever le droit d'écriture à tous les dossiers sans toucher aux autres fichiers
    6. #utile par exemple pour appliquer le droit d'exécution seulement aux dossiers pour pouvoir les parcourir sans pour autant rendre les autres fichiers exécutables
  10. 10 months ago and saved by 1 other
    1. # Boot on a live CD and open a console. sda1 is supposed to be the partition containing the OS
    2. # 1/ Restore GRUB
    3. mount -t proc none /dev/sda1/proc
    4. mount -o bind /dev /dev/sda1/dev
    5. chroot /dev/sda1/ /bin/bash
    6.  
    7. /usr/sbin/grub
    8. grub > root(hd0,0)    # 0->a, 1->b ...      #1->0, 2->1 ...
    9. grub > setup(hd0)
    10. grub > quit
    11.  
    12. # 2/ Check if partition is bootable
    13. fdsik /dev/sda
    14. fdisk > p      # print the partition table
    15. fdisk > a      # toggle a bootable flag
    16. fdsik > 1
    17. fidsk > w
    18.  
    19. # 3/ Reboot !! That's done
  11. 11 months ago and saved by 1 other
    1. # rename all .jpeg files to .jpg
    2. for file in *.jpeg; do mv $file ${file%.jpeg}.jpg; done
    3.  
    4. # make all the files in the current directory lowercase
    5. for file in *; do mv $file $(echo $file | tr [[:upper:]] [[:lower:]]); done

First / Previous / Next / Last / Page 1 of 3 (21 posteets)