Script Shell

Temps de lecture approximatif : 4 minutes

Le script Shell

Un script shell permet d’automatiser une série d’opérations. Il se présente sous la forme d’un fichier contenant une ou plusieurs commandes qui seront exécutées de manière séquentielle. Les deux sites ci-dessous vous apporterons une explication plus détaillée:
http://doc.ubuntu-fr.org/tutoriel/script_shell
http://openclassrooms.com/courses/reprenez-le-controle-a-l-aide-de-linux/introduction-aux-scripts-shell

Skeletons utilisés pour mes scripts shell

Vous trouverez ci-dessous quelques exemples que je propose pour débuter et constituer vos scripts shell. Ces lignes de codes peuvent être certainement optimisées 😉
Si vous avez des idées d’amélioration, n’hésitez pas à apporter vos commentaires. Merci d’avance à ceux qui voudront contribuer.

 

Exemple d’entête

#!/bin/bash 
# 
# NAME: 
# AUTHOR(S), CONTRIBUTOR(S): 
# VERSION: 0.1 
# LAST UPDATE: 
# FUNCTION: 
# 
# DEPENDENCIES: 
# 
# USAGE:          my_script_name "-h" 
# 
# INSTRUCTIONS: 
# 
# LICENCE: 
# 
# Copyright (c) 2013 My Name. (http://www.opours.net) All Rights Reserved. 
# WARNING: This program as such is intended to be used by professional 
# programmers who take the whole responsability of assessing all potential 
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software 
# Service Company This program is Free Software; you can redistribute it  
# and/or modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation; either version 2 
# of the License, or (at your option) any later version. 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
# GNU General Public License for more details. 
# You should have received a copy of the GNU General Public License 
# 
#########################################################################

 

 Exemple de syntaxe qui permettra la prise en charge d’options passées au script et l’affichage d’un message à l’écran suivant le type (VERBOSE, DEBUG, ERROR ou INFO).

 
#!/bin/bash 
# 
# NAME: 
# AUTHOR(S), CONTRIBUTOR(S): 
# VERSION: 0.1 
# LAST UPDATE: 
# FUNCTION: 
# 
# DEPENDENCIES: 
# 
# USAGE:          monscript "-h" 
# 
# INSTRUCTIONS: 
# 
# LICENCE: 
# 
# Copyright (c) 2013 My Name. (http://www.opours.net) All Rights Reserved. 
# WARNING: This program as such is intended to be used by professional 
# programmers who take the whole responsability of assessing all potential 
# consequences resulting from its eventual inadequacies and bugs.
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software 
# Service Company This program is Free Software; you can redistribute it  
# and/or modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation; either version 2 
# of the License, or (at your option) any later version. 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
# GNU General Public License for more details. 
# You should have received a copy of the GNU General Public License 
# 
#########################################################################
#
#
#
#################
# Used variables
#################
#
PATH="/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
PID_FILE="/tmp/monscript.pid"
SCRIPTDIR=$(dirname $(readlink -f $0))
SCRIPT_VERSION="0.1"

# Header
s_header () {
        echo ""
        echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
        echo "++                 monscript v$SCRIPT_VERSION                                   ++"
        echo "++                                                                  ++"
        echo "++ Written by opours.net (info@opours.net)                  ++"
        echo "++ Script function: Mon script permet....                           ++"
        echo "++                                                                  ++"
        echo "++ Licence: GNU/GPL                                                 ++"
        echo "++                                                                  ++"
        echo ""
        echo "Start at: `date`"
        echo ""
}

s_footer () {
    echo "++                                                                  ++"
    echo "++                                                                  ++"
    echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    echo ""
}

# Help
script_help () {
                s_header
                echo "+--------------------------------------------------+"
                echo "|                                                  |"
                echo "| USAGE:  monscript  [options]              "
                echo "|                                                  "
                echo "| Options:                                         "
        echo "|          -g: Put group name     "
        echo "|          -m: Put machine name   "
        echo "|          -c: Put hardware command      "
        echo "|          -d: Active debug mode [optional]        "
        echo "|                                                  "
        echo "| Example:                                         "
        echo "|                                                  "
        echo "|         monscript -g FIREWALL_CISCO -m cisco-fw -c \"show flash;show inventory\"   "
        echo "|                                                  "
        echo "|                                                  |" 
                echo "+--------------------------------------------------+"
                echo ""
        s_footer
                exit 1
}

DEBUG_STATUS=0
STATUS_GROUP_NAME=0
STATUS_MACH_NAME=0
STATUS_CMD=0

while [ $# -gt 0 ]; do

        if [ "$1" = "?" ] ; then
                script_help
        fi
        case "$1" in
        
             -h|h)   echo ""
                     echo "help me !"
                     script_help
                     ;;

            -d|d) echo ""
                  echo "[INFO]: Verbose mode ACTIVATE."
                  DEBUG_STATUS=1
                  ;;

            -g) echo ""
                # Set GROUP_NAME variable's: $2"
                GROUP_NAME=$2
                STATUS_GROUP_NAME=1
                ;;

            -m) echo ""
                # Set MACH_NAME variable's: $2"
                MACH_NAME=$2
                STATUS_MACH_NAME=1
                ;;

            -c) echo ""
                # Set REMOTE_CMD variable's: $2"
                REMOTE_CMD=$2
                STATUS_CMD=1
                ;;
                        
       esac
       shift
done

if [ "$STATUS_GROUP_NAME" != "1" ] || [ "$STATUS_MACH_NAME" != "1" ] || [ "$STATUS_CMD" != "1" ]
    then
        echo ""
        echo ""
        echo "Value for script options: $STATUS_GROUP_NAME; $STATUS_MACH_NAME; $STATUS_CMD"
        echo "Bad command !"
        script_help
fi
# Remove PID file
remove_pid_file () {
        echo ""
        v "[END]: Remove PID file..."
        echo ""
        rm $PID_FILE
        echo ""
}

# Nice debugging messages...
function e {
        echo -e $(date "+%F %T"):  $1
}
function v {
        if [ "$DEBUG_STATUS" != "0" ]
                then
                        echo -e [VERBOSE MODE]: $(date "+%F %T"):  $1
        fi
}
function die {
        e "[CRITICAL ERROR]: $1" >&2
        e ""
}
function warn {
        e "[WARN]: $1" 
}
###############################
# Check if script is running...
###############################
#
v "[CONTROL]: Check if script is already run"
if test -f $PID_FILE
        then
                v "--OK-- I found : $PID_FILE"
                pidof -x $0
                e ""
                die "--BAD-- /!\ : $PID_FILE was found ! $0 as already running...Thank you to wait before restarting this script !  "
                exit 1
        else
                v "--OK-- I found nothing...script is not running...I'll continue !"
                v ""
fi

###################################
# Create PID file to lock script...
###################################
#
ISRUNNING=$(pidof -x $0)
echo $ISRUNNING > $PID_FILE
#
#
####################
# Global section...
####################
#
s_header
#
echo "suite de mon script"
remove_pid_file
s_footer
exit 0


“La connaissance a plus de valeur et s’accroît rapidement lorsqu’elle est partagée et accessible librement…”

Ce document est publié sous licence Creative Commons
Attribution, Partage à l’identique, Contexte non commercial 3.0 : http://creativecommons.org/licenses/by-nc/3.0/

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Le temps imparti est dépassé. Merci de saisir de nouveau le CAPTCHA.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.