Manage Script Bash

TIPS & TRICKS

To search the contents of the man pages

# man -k searchterm 
# man -K searchterm

Script bash tasks examples

Script bash 1

| Create a script file:
| - if the paramater is “GM” it outputs “good morning”
| - if it is “GN”, it outputs “good night”

#!/bin/bash

# Vérifie si exactement un argument est fourni
if [ $# != 1 ]; then
echo "Erreur : Ce script nécessite exactement un argument (GM ou GN)."
exit 1
fi

# Vérifie la valeur de l'argument
if [ "$1" = "GM" ]; then
echo "Good Morning"
elif [ "$1" = "GN" ]; then
echo "Good Night"
else
echo "Paramètre non valide. Utilisez GM ou GN."
fi
# chmod 755 script.sh
# ./script.sh GM

Script bash 2

| Question: Take a input as a file and then print its contents line-by-line
| - if no input give then print: Usage: ./readfile.sh
| - it should take only one argument

#!/bin/bash

# Vérifie qu'il y a exactement un argument
if [ $# != 1 ]; then
echo "Usage: ./readfile.sh <FILE-NAME>"
exit 1
fi

# Lire et afficher le contenu du fichier ligne par ligne
while IFS= read -r line; do
echo "$line"
done < "$1"

Script bash 3

| Question: Script should take only one input as argument
| - It should print
| - YES for Y/y
| - NO for N/n
| - UNKNOWN for anything else
| - For anything else print: Usage: ./caseex.sh Y|N

#!/bin/bash

# Vérifie qu'il y a exactement un argument
if [ $# != 1 ]; then
echo "Usage: ./caseex.sh Y|N"
exit 1
fi

# Vérifie la valeur de l'argument avec une construction case
case "$1" in
Y|y)
echo "YES"
;;
N|n)
echo "NO"
;;
*)
echo "UNKNOWN"
;;
esac

Script bash 4

| Question: Script should take one argument only with values
| - Yes|YES it should print awesome
| - No|NO it should print That’s bad
| - For anything else it should print it’s usage as: Usage: ./ifelse.sh Yes|No

#!/bin/bash

# Vérifie qu'il y a exactement un argument
if [ $# -ne 1 ]; then
echo "Usage: ./ifelse.sh Yes|No"
exit 1
fi

# Vérifie la valeur de l'argument
case "$1" in
Yes|YES)
echo "Awesome"
;;
No|NO)
echo "That's bad"
;;
*)
echo "Usage: ./ifelse.sh Yes|No"
;;
esac

Script bash 5

| Create a newsearch script called
| The script is placed /usr/binunder
| This script is used to find /usrall files that are greater than 30k, but less than 50k and have SUIDpermissions, and place these file names in the /root/newfilesfile

#!/bin/bash

touch /root/newfiles
find /usr -size +30k -size -50k -perm /u=s > /root/newfiles
# chmod +x /usr/bin/newsearch
# ./usr/bin/newsearch
# cat /root/newfiles

Script bash 6

| Create a myresearch script called
| The script is placed /usr/binunder
| This script is used to find /usrall files that are smaller than 10m and have modification Group ID permissions s, and place these files /root/myfilesunder

#!/bin/bash

mkdir /root/newfiles
find /usr -size -10M -perm /u=s cp -a {} /root/newfiles \;
# chmod +x /usr/bin/newsearch
# ./usr/bin/newsearch
# cat /root/newfiles

Script bash 7

| Question: Script should take a number as an argument and should print HACK that may times
| - Example forex.sh 4 will print HACK 1, HACK 2, HACK 3, HACK 4 in diffrent lines
| - If number is less than or equal to zero then it should print: number less than 0
| - If inout is not a number than it should print: Input not a number
| - For any other number of inputs it should print: Usage ./forex.sh
| - If input is NOT a number it should throw error code 6 and should print Input not a number.

#!/bin/bash

# Vérifie qu'il y a exactement un argument
if [ $# -ne 1 ]; then
echo "Usage: ./forex.sh <NUMBER>"
exit 1
fi

# Vérifie si l'argument est un nombre
if ! [[ "$1" =~ ^-?[0-9]+$ ]]; then
echo "Input not a number"
exit 6
fi

# Vérifie si le nombre est <= 0
if [ "$1" -le 0 ]; then
echo "Number less than or equal to 0"
exit 0
fi

# Affiche "HACK" autant de fois que le nombre donné
for i in $(seq 1 "$1"); do
echo "HACK $i"
done

Script bash 8

| Question: Script should take only one input numberic input
| - It should print HACK N that many times
| - If number of agruments is not 1 then it should print: Usage: ./whilex.sh
| - If input is not number then print: NOT a number
| - If number is less than equal to 0 then print: Number not > 0
| - We must use while loop to implement it

#!/bin/bash

# Vérifie qu'il y a exactement un argument
if [ $# -ne 1 ]; then
echo "Usage: ./whilex.sh <NUMBER>"
exit 1
fi

# Vérifie si l'argument est un nombre
if ! [[ "$1" =~ ^-?[0-9]+$ ]]; then
echo "NOT a number"
exit 1
fi

# Vérifie si le nombre est supérieur à 0
if [ "$1" -le 0 ]; then
echo "Number not > 0"
exit 1
fi

# Boucle while pour afficher "HACK N" N fois
count=1
while [ "$count" -le "$1" ]; do
echo "HACK $count"
count=$((count + 1))
done

Script bash 9

| Write a bash shell script that creates three users:
| - user555, user666, user777
| - with nologin shell
| - passwords matching their names
| The script should also
| - extract names of these three new users from the /etc/passwd
| - redirect them to /var/tmp/newusers

#!/bin/bash

# Liste des utilisateurs à créer
users=("user555" "user666" "user777")

# Crée les utilisateurs avec le shell /sbin/nologin et le mot de passe correspondant à leur nom
for user in "${users[@]}"; do
# Crée l'utilisateur avec le shell /sbin/nologin
useradd -m -s /sbin/nologin "$user"

# Définit le mot de passe de l'utilisateur
echo "$user:$user" | chpasswd

echo "Created user $user with password matching their username."
done

# Extrait les noms des nouveaux utilisateurs de /etc/passwd et les redirige vers /var/tmp/newusers
grep -E "user555|user666|user777" /etc/passwd > /var/tmp/newusers
echo "Extracted user details saved to /var/tmp/newusers."

exit 0

Script bash 10

| Create a bash script that display
| - the hostname,
| - users that are currently logged in

#!/bin/bash 

echo " Display sys info "
/usr/bin/hostnamectl
echo " The users that are currently logged in: "
/usr/bin/who

Script bash 11

| Create a bash script that shows
| - total count of the supplied arguments
| - value of the first argument
| - PID of the script
| - and all the supplied arguments

#!/bin/bash

# Affiche le nombre total d'arguments
echo "Total arguments supplied: $#"

# Affiche la valeur du premier argument
if [ $# -ge 1 ]; then
echo "First argument: $1"
else
echo "No arguments provided."
fi

# Affiche le PID du script en cours
echo "Script PID: $$"

# Affiche tous les arguments fournis
if [ $# -ge 1 ]; then
echo "All arguments: $@"
else
echo "No arguments provided."
fi

exit 0

Script bash 12

| Create a bash script that can create user10, user20 and user30 accounts with each account is create a message saying “The account is created successfuly” will be displayed otherwise the script will terminate .
| In case of a successful account creation assign the user account a password as their username

#!/bin/bash

# Fonction pour créer un utilisateur
create_user() {
local user=$1

# Création de l'utilisateur
useradd "$user" -m -s /sbin/nologin

# Vérification de la réussite de la création
if [ $? -eq 0 ]; then
# Définition du mot de passe comme étant le nom de l'utilisateur
echo "$user:$user" | chpasswd

# Vérification de la réussite de la définition du mot de passe
if [ $? -eq 0 ]; then
echo "The account $user is created successfully"
else
echo "Failed to set password for $user. Script terminating."
exit 1
fi
else
echo "Failed to create user $user. Script terminating."
exit 1
fi
}

# Création des utilisateurs
create_user "user10"
create_user "user20"
create_user "user30"

exit 0

Script bash and cron

Script bash and cron 1

| Créez un script bash nommé backup.sh qui archive le répertoire /data vers /backup/data.tar.gz chaque jour à 2h00.”

Créer le script backup.sh :

#!/bin/bash
tar -czf /backup/data.tar.gz /data

Rendre le script exécutable :

# chmod +x /backup.sh

Planifier la tâche cron :

# crontab -e
0 2 * * * /backup.sh

Script bash and cron 2

| As a System Administrator you are responsible to take a backup of your /etc directory every night.
| Build a shell script to take a backup of the /etc/directory using the tar command.
| The backup script should be named as /root/backup.sh.
| Schedule this script to run at 11:00 PM every night – except Sundays.

#!/bin/bash 

tar -cvf etc_backup.tar /etc/
# chmod +x /root/backup.sh
# /root/backup.sh
# crontab -e 
* 23 * * 1-6 /root/backup.sh

Exemples de scripts shell basiques

Exemple de script shell typique avec des structures de contrôle :

#!/bin/bash

# Demander un nombre
echo "Entrez un nombre :"
read nombre

# Vérifier si le nombre est positif ou négatif
if [ $nombre -gt 0 ]; then
echo "Le nombre est positif"
elif [ $nombre -lt 0 ]; then
echo "Le nombre est négatif"
else
echo "Le nombre est zéro"
fi

# Compter de 1 à N avec une boucle while
i=1
while [ $i -le $nombre ]; do
echo "HACK $i"
((i++))
done

Documentations

Internet
Git
ChatGPT

> Partager <