Skip to content

Bash Script Examples

This section contains examples of Bash scripting in Unix-like systems. These scripts cover various aspects of shell scripting, including basic commands, variable usage, control structures, and more. Below is a list of the Bash script files with descriptions and links to their content.

File Name Description Link
1_hello.sh Demonstrates the use of the echo command with different string delimiters 1_hello.sh
2_clean.sh Removes the backup files (*~) of the current directory with rm -f -- ./*~ 2_clean.sh
3_variables_01.sh Demonstrates variables and their contents using echo 3_variables_01.sh
3_variables_02.sh Illustrates the difference between simple and double quotes (expansion of $BAD or not) 3_variables_02.sh
4_read.sh Reads a file name with read -r, checks that it exists, then removes it with rm -i 4_read.sh
5_substitution_01.sh Shows command substitution (example 1) 5_substitution_01.sh
5_substitution_02.sh Command substitution to know whether backup files exist on the desktop, then find -exec rm -i to remove them one by one 5_substitution_02.sh
5_substitution_03.sh Command substitution in a file name: backup-$(date ...).tar.gz archive of the directory given as parameter (5_substitution_03.sh DIRECTORY) 5_substitution_03.sh
6_arithmetic_01.sh Illustrates arithmetic operations in Bash 6_arithmetic_01.sh
6_arithmetic_02.sh A minimal calculator with $(( )) (integers only; division by zero refused; the bc command is more powerful) 6_arithmetic_02.sh
7_exp01_user.sh Demonstrates how to test expressions with if statements 7_exp01_user.sh
7_exp02_number_1.sh Tests an expression with nested if statements ([ ... -lt ... ]), after checking that the input is an integer 7_exp02_number_1.sh
7_exp02_number_2.sh Same test with [[ ... && ... ]] 7_exp02_number_2.sh
7_exp02_number_3.sh Same test with the arithmetic command (( x > 1 && x < 10 )) 7_exp02_number_3.sh
7_exp02_number_4.sh Same test with two [ ] joined by && 7_exp02_number_4.sh
8_parameters.sh Demonstrates how to get arguments from a script 8_parameters.sh
9_case.sh Shows the use of the case statement 9_case.sh
10_for_01.sh Demonstrates iteration using for loop 10_for_01.sh
10_for_02.sh Demonstrates iteration using for loop 10_for_02.sh
10_for_03.sh Loops over the files of the current directory: name, extension (${file%%.*}, ${file##*.}) and count 10_for_03.sh
11_function_01.sh Shows the use of a simple function 11_function_01.sh
11_function_02.sh Demonstrates functions with parameters 11_function_02.sh
11_while_01.sh Demonstrates iteration using while loop (sum from 1 to a positive integer entered by the user) 11_while_01.sh
11_while_menu.sh Shows a menu using while loop 11_while_menu.sh
12_arrays.sh Demonstrates the use of arrays in Bash 12_arrays.sh
13_grepedit.sh Opens in vim the files that contain a given word (grep -q -F -w --: the word is neither a regular expression nor an option) 13_grepedit.sh
create_project.sh A complete script to create a C project structure (Makefile, Doxyfile, MinUnit downloaded with curl); confirms before deleting a project :-) create_project.sh

Sources

10_for_01.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate the use of a 'for' loop in Bash

# Looping through a list of programming languages
echo "Listing my favorite programming languages:"

for language in Java C Python Scala Caml R; do
    echo "I like $language"
    sleep 1  # Pausing for 1 second between each iteration for demonstration purposes
done

echo "Loop completed."
10_for_02.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Another simple script to demonstrate the use of a 'for' loop for summing numbers

sum=0  # Initialize the accumulator

echo "Adding numbers from 1 to 6:"

for i in 1 2 3 4 5 6; do
    sum=$((sum + i))  # Accumulate the sum
    echo "After adding $i, sum is: $sum"
done

echo "Final sum: $sum"
10_for_03.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to display file extensions, list files, and count the number of files in the current directory
# It displays extensions, files and the number of files in the current directory.
# This also can be done using:
#   ls | wc -l
# or in a more robust way:
#   find ./ -type f | wc -l
#
count=0
LIST=""

for file in *; do
    if [ -f "$file" ]; then  # Check if it's a regular file
        name=${file%%.*}       # before the first dot
        extension=${file##*.}  # after the last dot
        echo "$name -> $extension"
        LIST="$LIST $file"
        count=$((count + 1))   # counted here: a name may contain spaces
    fi
done

echo "List of files: $LIST"
echo
echo "Number of files: $count"
11_function_01.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# A script to demonstrate the use of functions in Bash

# Function definition
display_message () {
  local message=$1  # Using a parameter within the function
  echo "We are in the display_message function."
  echo "Message: $message"
  echo "Now we exit the function."
  return 0  # Indicate successful execution
} 

# Function call with a parameter
echo "Calling the display_message function..."
display_message "Hello from the function!"

# Check the return status of the function
if [ $? -eq 0 ]; then
  echo "Function executed successfully."
else
  echo "Function execution failed."
fi
11_function_02.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate a more complex function in Bash

less_simple () {
    local JUST_A_SECOND=$1  # Sleep duration as a parameter
    local counter=0
    local REPETITIONS=$2  # Number of repetitions as a parameter

    echo "And now we run..."
    while [ "$counter" -lt "$REPETITIONS" ]; do
        echo "<------- FUNCTIONS are useful (${counter}) ------>"
        sleep "$JUST_A_SECOND"
        counter=$((counter + 1))  # Increment counter
    done
}

# Call the function with parameters: sleep duration and number of repetitions
less_simple 1 20
11_while_01.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script using a while loop to calculate the sum of all numbers from 1 to a user-provided number

echo -n "Enter a positive number: "
read -r number

if ! [[ $number =~ ^[0-9]+$ ]]; then
    echo "A positive integer is expected." >&2
    exit 1
fi

sum=0
i=1

# Calculate the sum
while [ "$i" -le "$number" ]; do
  sum=$((sum + i))
  i=$((i + 1))
done

echo "The sum from 1 to $number is: $sum"
11_while_menu.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate a simple interactive menu using a while loop

clear
continue_loop="y"
while [ "$continue_loop" = "y" ]; do
    echo "Menu"
    echo "===="
    echo "D: Display the date"
    echo "U: Display connected users"
    echo "W: Display the path of the working directory"
    echo "Q: Quit"
    echo

    # Read user choice in silent mode
    read -s -r choix
    echo

    # Process user choice
    case "$choix" in
        [Dd]) date ;;
        [Uu]) who ;;
        [Ww]) pwd ;;
        [Qq]) continue_loop="n" ;;
        *) echo "Not a valid choice! Try again." ;;
    esac

    echo
    read -r -p "Press any key to continue..." -n 1 -s
    clear
done 

echo "Exiting the menu. Goodbye!"
12_arrays.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to demonstrate the use of arrays in Bash

# Define an array of programming languages
languages=("C" "C++" "Java" "Scala" "Python")

# Iterate over the array and print each language
echo "List of programming languages:"
for language in "${languages[@]}"; do
    echo "Language: $language"
done

# Add a new language to the array
echo "Adding 'Rust' to the list of programming languages..."
languages+=("Rust")

# Print the updated array
echo "Updated list of programming languages:"
for language in "${languages[@]}"; do
    echo "Language: $language"
done

# Demonstrating other array operations
echo "The first language in the list is: ${languages[0]}" # Accessing the first element
echo "The list of languages contains ${#languages[@]} elements." # Number of elements in the array
13_grepedit.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Script to open files containing a specific word in Vim

if [ $# -le 1 ]; then
  echo "Usage: $0 <word> <file1> [<file2> ...]"
  exit 1
fi

word=$1
shift

echo "Searching for files containing the word '$word'..."
while [ $# -gt 0 ]; do
  if [ -f "$1" ] && [ -r "$1" ] && grep -q -F -w -- "${word}" "$1"; then
    vim "$1"
  else
    echo "Word '$word' not found or file '$1' cannot be read."
  fi
  shift
done
1_hello.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script that says hello using the echo command and different string delimiters

# Double quotes allow variable expansion and command substitution
echo "Bonjour à vous !"

# Separate strings are concatenated with a space in between
echo "Bonjour" "à" "vous" "!"

# Single quotes prevent variable expansion and command substitution
echo 'Bonjour à vous !'

# Without quotes, the string is subject to word splitting and globbing
echo Bonjour à vous !

# Escaped double quotes are treated as part of the string
echo \"Bonjour à vous !\"

# Escaped single quotes are treated as part of the string
echo \'Bonjour à vous !\'
2_clean.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# This script removes the backup files (*~) of the current directory.
# rm -f does not fail when there is no such file; -- protects names that
# begin with a dash.
if rm -f -- ./*~; then
    echo "Temporary files are removed!"
fi
3_variables_01.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to show variables and their contents
MESSAGE="Bonjour"
message="bonjour"
nom="Jean"
PI="3.14159"  # Use . for decimal point

echo "MESSAGE: $MESSAGE"
echo "message: $message"
echo "\$MESSAGE: ${MESSAGE}"
echo "\$message: ${message}"

printf "\nBonjour %s !\nSavez-vous que le nombre PI vaut %s ?\n\n" "$nom" "$PI"
3_variables_02.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to show the difference between simple and double quotes

# Double quotes: Variable values are expanded
BAD="great"
UNIX="Unix is a $BAD system!"
echo "$UNIX"  # Output: Unix is a great system!

echo ""

# Single quotes: Variables are treated as literal strings
BAD="terrible"
WINDOWS='Ms-Windows is a $BAD system!'
echo "$WINDOWS"  # Output: Ms-Windows is a $BAD system!

# Demonstrating escaped characters
echo "Using double quotes with escaped characters: \$BAD"
echo 'Using single quotes with escaped characters: \$BAD'

# Demonstrating command substitution
echo "Command substitution with double quotes: $(date)"
echo 'Command substitution with single quotes: $(date)'
4_read.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to read some input.

echo -n "Enter the name of the file to remove: "
read -r filename      # -r: a backslash in the name is kept as is
if [ ! -e "${filename}" ]; then
    echo "${filename}: no such file." >&2
    exit 1
fi
if rm -i -- "${filename}"; then
    echo "File have been removed."
else
    echo "File removal was cancelled or failed."
fi
5_substitution_01.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to show the command substitution

# Using backticks for command substitution
COMMAND1=`ls`
echo "Listing files using backticks:"
echo "$COMMAND1"

echo ""

# It is recommended to use $(...) for command substitution due to better readability and nesting ability
echo "It can also be done using \$(...):"
COMMAND2=$(ls)
echo "$COMMAND2"

# Example of nested command substitution
echo ""
echo "Nested command substitution example:"
COMMAND3=$(echo "Today is $(date +%A)")
echo "$COMMAND3"

# Checking if the command was successful
# The assignment returns the exit status of the command run by $(...)
if ! COMMAND4=$(ls non_existent_directory); then
    echo "Failed to execute command (COMMAND4 is empty: '$COMMAND4')"
fi
5_substitution_02.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to show how to use substitution in a more complex command

echo "Remove backup files on the desktop"

# The substitution $(...) is only used to know whether there are files
backup_files=$(find ~/Desktop/ -name "*.*~")
if [ -z "$backup_files" ]; then
    echo "No backup files found."
else
    echo "Removing backup files..."
    # find runs rm itself: names with spaces are safe, and rm -i can ask the
    # question on the terminal (with "| xargs", its stdin would be the pipe)
    find ~/Desktop/ -name "*.*~" -exec rm -i -v {} \;
fi
5_substitution_03.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# This script demonstrates using command substitution to create a dynamically named tarball backup

echo "Define BACKUP as ./backup-\$(date +%Y-%m-%d).tar.gz"
BACKUP="./backup-$(date +%Y-%m-%d).tar.gz"
echo "BACKUP filename is set to $BACKUP"

# The directory to save is given as parameter (not "." : the archive would contain itself)
if [ $# -ne 1 ]; then
    echo "Usage: $0 DIRECTORY" >&2
    exit 1
fi
SOURCE_DIR="$1"
if [ -d "$SOURCE_DIR" ]; then
    echo "Creating a tarball backup of $SOURCE_DIR"
    if tar -czf "${BACKUP}" "$SOURCE_DIR"; then
        echo "Backup successfully created at ${BACKUP}"
    else
        echo "Failed to create backup."
    fi
else
    echo "Source directory $SOURCE_DIR does not exist. Backup not created."
fi
6_arithmetic_01.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# A simple script to demonstrate arithmetic operations in Bash

# Using "let" for arithmetic operations
echo "Using let for arithmetic:"
let x=8*2+3
echo "Let x = 8 * 2 + 3, x = $x"

let y=5+x
echo "Let y = 5 + x, y = $y"

# Using "$((...))" for arithmetic expansion (recommended method)
echo "Using \$(()) for arithmetic expansion:"
echo "\$((8 * 2 + 3)) = $((8 * 2 + 3))"

# Demonstrating more complex operations
echo "More complex operations:"
echo "\$((x * y)) = $((x * y))"
echo "\$((x % y)) (modulo) = $((x % y))"

# Deprecated "$[]" syntax for arithmetic (should be avoided)
echo "Deprecated \$[] syntax for arithmetic (not recommended):"
VALUE=$[12+20]
echo "\$[12 + 20] = $VALUE"
echo "\$[2 * \$VALUE] = $[2 * $VALUE]"
echo "\$[\$VALUE / 2] = $[$VALUE / 2]"

# Note: The use of $[] for arithmetic is deprecated and should be avoided in favor of $((...))
6_arithmetic_02.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Another simple script to show some arithmetic operations

echo -n "Enter the first number: "; read -r x
echo -n "Enter the second number: "; read -r y

# Integers only (an optional minus sign, then digits)
if ! [[ $x =~ ^-?[0-9]+$ && $y =~ ^-?[0-9]+$ ]]; then
    echo "Integers are expected." >&2
    exit 1
fi
if [ "$y" -eq 0 ]; then
    echo "Division by zero: the second number must not be 0." >&2
    exit 1
fi

# Inside $(( )), variables can be written without $
sum=$((x + y))
difference=$((x - y))
product=$((x * y))
ratio=$((x / y))
remainder=$((x % y))

# Displaying results
echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Ratio: $ratio"
echo "Remainder: $remainder"
7_exp01_user.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate testing expressions with if statements

echo -n "Enter your username: "
read -r username

if [[ -z "$username" ]]; then
    echo "No username entered. Please try again."
    exit 1
fi

if [[ "$username" == "$USER" ]]; then 
    echo "Hello, $username. How do you feel today?"
else 
    echo "You are not $USER! Who are you, $username?"
fi
7_exp02_number_1.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# A script to demonstrate testing an expression and arithmetic operations

echo -n "Enter an integer value x such as: 1 < x < 10 : "
read -r x

# Stop at once if the input is not an integer (otherwise: "integer expression expected")
if ! [[ $x =~ ^-?[0-9]+$ ]]; then
    echo "Bad choice! '$x' is not an integer." >&2
    exit 1
fi

if [ "$x" -lt 10 ]
then
  if [ "$x" -gt 1 ]
  then 
    echo "$x*$x=$((x*x))"
  else 
    echo "Bad choice! The number must be higher than 1."
  fi
else
  echo "Bad choice! The number must be lower than 10."
fi
7_exp02_number_2.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate testing an expression within a range

echo -n "Enter an integer value x such as: 1 < x < 10 : "
read -r x

# Stop at once if the input is not an integer (otherwise: "integer expression expected")
if ! [[ $x =~ ^-?[0-9]+$ ]]; then
    echo "Bad choice! '$x' is not an integer." >&2
    exit 1
fi

# Check if the integer is in the range 1 < x < 10
if [[ "$x" -gt 1 && "$x" -lt 10 ]]; then
    echo "$x*$x=$((x*x))"
else
    echo "Bad choice! The number must be strictly between 1 and 10."
fi
7_exp02_number_3.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Same test as 7_exp02_number_2.sh, written with the arithmetic command (( )):
# inside (( )), < and > compare numbers and variables need no $

echo -n "Enter an integer value x such as: 1 < x < 10 : "
read -r x

# Stop at once if the input is not an integer (otherwise: "integer expression expected")
if ! [[ $x =~ ^-?[0-9]+$ ]]; then
    echo "Bad choice! '$x' is not an integer." >&2
    exit 1
fi

if (( x > 1 && x < 10 )); then
    echo "$x*$x=$((x*x))"
else
    echo "Bad choice! The number must be strictly between 1 and 10."
fi
7_exp02_number_4.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A simple script to show how to test an expression

echo -n "Enter an integer value x such as: 1 < x < 10 : "
read -r x

# Stop at once if the input is not an integer (otherwise: "integer expression expected")
if ! [[ $x =~ ^-?[0-9]+$ ]]; then
    echo "Bad choice! '$x' is not an integer." >&2
    exit 1
fi

if [ "$x" -gt 1 ] && [ "$x" -lt 10 ]
then 
  echo "$x*$x=$((x*x))"
else
  echo "Bad choice! The number must be strictly between 1 and 10."
fi
8_parameters.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate parameter manipulation by moving a file to a trash directory

if [ $# -eq 1 ]; then
  file_to_move="$1"

  # Check if the file exists
  if [ ! -f "$file_to_move" ]; then
    echo "Error: File '$file_to_move' not found."
    exit 1
  fi

  # Create the trash directory if it doesn't exist
  if [ ! -d trash ]; then
    mkdir trash || { echo "Failed to create trash directory"; exit 1; }
  fi

  # Move the file to the trash directory with confirmation
  mv -i -v "$file_to_move" trash
else
  echo "Usage: $0 <filename>"
  echo "Example: $0 document.txt"
  exit 1
fi
9_case.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# Copyright (C) 1995-2026 Alain Lebret
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# A script to demonstrate the use of 'case' in Bash for pattern matching

echo -n "Enter an integer value x such as: 1 < x < 10 : "
read -r x

echo "Checking the value of x using case statement:"
case $x in
  [2-9]) echo "x = $x";;
  *) echo "Bad choice! The number must be between 2 and 9.";;
esac
create_project.sh

View on GitHub

#!/bin/bash

#
# ENSICAEN
# 6 Boulevard Maréchal Juin
# F-14050 Caen Cedex
#
# Unix System Programming Examples / Exemplier de programmation système Unix
# "Shell bash" / "Interpréteur de commandes bash"
#
# This script automates the setup and management of C programming projects.
# It provides functions for creating, opening, compiling, and archiving projects.
#
# Authors: Alain Lebret
# Dependencies: bash, gcc, make, curl (optional: doxygen)
# Usage: Run the script and follow the on-screen menu options.
#
# This script is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# GLOBALS
#
DEFAULT_PROJECT_PATH=""
AUTHOR1="Jean Saigne"
AUTHOR2="Jacques Horde"
DEFAULT_AUTHORS="$AUTHOR1 & $AUTHOR2"
DEFAULT_C_HEADER="/*
 * ENSICAEN
 * 6 Boulevard Marechal Juin
 * F-14050 Caen Cedex
 *
 * This file is owned by ENSICAEN students.
 * No portion of this document may be reproduced, copied
 * or revised without written permission of the authors.
 */"

DEFAULT_CC="gcc"
DEFAULT_CFLAGS="-Wall -Wextra -std=c11 -pedantic -g"
DEFAULT_HEADER_PATH="include"
DEFAULT_DOC_PATH="doc"
DEFAULT_LIBS="-lm"
DEFAULT_EXEC="prog.exe"

# Example of a directory configuration array
# Used by initialize_rep()
DEFAULT_DIR_STRUCTURE=("bin" "bin/tests" "${DEFAULT_DOC_PATH}" "etc" "${DEFAULT_HEADER_PATH}" "lib" "src" "tests")

# Errors are shown on screen and also kept in this log file
LOG_FILE=/tmp/create_project.log


# Fatal error: displays the message (screen and log file), then exits.
# Arguments:
#   $1 - Error message to display.
#   $2 - Name of the function where the error occurred.
function error() {
    echo "Error in function $2: $1!" | tee -a "$LOG_FILE" >&2
    exit 1
}

# Non-fatal error: displays the message (screen and log file) and returns,
# so that the menu goes on after a typing mistake.
# Arguments:
#   $1 - Error message to display.
function warn() {
    echo "Erreur : $1" | tee -a "$LOG_FILE" >&2
}

# Displays the help message for the script usage.
# Arguments:
#   None
# Usage:
#   help
function help() { 
    echo "$(basename "$0") est un script shell pour créer des projets C."
    exit 0
} 

# Initializes the project repository.
# Creates a new directory structure based on the selected project template.
# Globals:
#   DEFAULT_PROJECT_PATH
# Arguments:
#   None
# Returns:
#   0 if successful, 1 if the project already exists or fails to create directories.
function initialize_rep() {
    if [ ! -e "$DEFAULT_PROJECT_PATH" ]; then
       if ! mkdir "$DEFAULT_PROJECT_PATH"; then
          warn "La création du dossier pour le projet a échoué."
          return 1
       fi
       for dir in "${DEFAULT_DIR_STRUCTURE[@]}"; do
          mkdir -p "$DEFAULT_PROJECT_PATH/$dir"
          touch "$DEFAULT_PROJECT_PATH/$dir/.gitkeep"
       done
       return 0
    else
       warn "Le projet existe déjà"
       return 1
 fi
}


# Creates a README.md file in the project directory.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
# Arguments:
#   None
# Usage:
#   create_README
function create_README() {
   cat > "$DEFAULT_PROJECT_PATH/README.md"<<EOF
# Project $DEFAULT_PROJECT_PATH
## Description

A complete description of the project...

## Installation

A complete description of its installation...
make ...
## Usage 

A description of its usage...

## Dependancies

List of dependances... 

## Authors

$DEFAULT_AUTHORS
$(date)
EOF
}


# Customizes the Makefile parameters for the project.
# Prompts the user to input custom values for the compiler (CC) and 
# compiler flags (CFLAGS). If the user does not provide any input, 
# default values are used. This function allows the user to tailor 
# the build process to specific requirements or preferences.
#
# Globals:
#   DEFAULT_CC - The compiler to be used for the project (default: gcc).
#   DEFAULT_CFLAGS - The compiler flags to be used (default: -Wall -Wextra -std=c11 -pedantic -g).
#
# Arguments:
#   None
#
# Usage:
#   customize_makefile
function customize_makefile() {
    echo "Spécifiez le compilateur (par défaut : gcc) :"
    read -r input
    DEFAULT_CC=${input:-gcc}

    echo "Spécifiez les options du compilateur (par défaut : -Wall -Wextra -std=c11 -pedantic -g) :"
    read -r input
    DEFAULT_CFLAGS=${input:--Wall -Wextra -std=c11 -pedantic -g}

    echo "Spécifiez le dossier contenant les entêtes (par défaut : include) :"
    read -r input
    DEFAULT_HEADER_PATH=${input:-include}

    echo "Spécifiez les bibliothèques utilisées (par défaut : lm) :"
    read -r input
    DEFAULT_LIBS=${input:--lm}

    echo "Spécifiez le nom du programme exécutable (par défaut : prog.exe) :"
    read -r input
    DEFAULT_EXEC=${input:-prog.exe}
}

# Creates a Makefile in the project directory.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
#   DEFAULT_HEADER_PATH - The path of the header directory
#   DEFAULT_CFLAGS - The flags for the C compiler
#   DEFAULT_LIBS - the libraries to link with
#   DEFAULT_EXEC - The executable name
# Arguments:
#   None
# Usage:
#   create_Makefile
function create_Makefile() {
   echo "CC       = ${DEFAULT_CC}
RM       = rm
DOC      = doxygen
CPPFLAGS = -I ${DEFAULT_HEADER_PATH}
CFLAGS   = ${DEFAULT_CFLAGS}
LDFLAGS  = -L ./lib ${DEFAULT_LIBS}

.PHONY: all doc clean distclean

all: ./bin/${DEFAULT_EXEC}

./bin/${DEFAULT_EXEC}: ./src/main.o # And others .o
    \$(CC) \$< -o \$@ \$(LDFLAGS)

./src/%.o: ./src/%.c
    \$(CC) \$(CPPFLAGS) \$(CFLAGS) -c \$< -o \$@

doc:
    -@\$(DOC) ${DEFAULT_DOC_PATH}/Doxyfile

clean:
    -@\$(RM) ./src/*.o

distclean: clean
    -@\$(RM) ./bin/${DEFAULT_EXEC}" > "$DEFAULT_PROJECT_PATH"/Makefile
}

# Creates the main C source file in the project's source directory.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
#   DEFAULT_C_HEADER - C file header content.
# Arguments:
#   None
# Usage:
#   create_main
function create_main() {
   cat > "$DEFAULT_PROJECT_PATH/src/main.c"<<EOF
$DEFAULT_C_HEADER 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
   #define USAGE "Usage : %s text_file\n"

   if ((argc > 1) && (strcmp("-h", argv[1]) == 0)) {
      fprintf(stderr, USAGE, argv[0]);
      return EXIT_FAILURE;
   }   

   /* Your code here ... */
   return EXIT_SUCCESS;
}
EOF
}

# Creates a Doxygen configuration file in the project's documentation directory.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
#   DEFAULT_HEADER_PATH - The path of the headers directory.
#   DEFAULT_DOC_PATH - The path of the doxygen dcumentation/
# Arguments:
#   None
# Usage:
#   create_Doxyfile
function create_Doxyfile() {
   cat > "$DEFAULT_PROJECT_PATH/doc/Doxyfile"<<EOF
PROJECT_NAME = "$DEFAULT_PROJECT_PATH"
OUTPUT_DIRECTORY = $DEFAULT_DOC_PATH
FILE_PATTERNS = $DEFAULT_HEADER_PATH/*.h src/*.c
GENERATE_HTML = YES
GENERATE_LATEX = NO
GENERATE_RTF = NO
EOF
}

# Downloads the MinUnit testing framework files into the project.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
# Arguments:
#   None
# Usage:
#   copy_minunit
function copy_minunit() {
    local url=https://raw.githubusercontent.com/siu/minunit/master
    # curl is present on macOS and on most Linux systems (wget is not on macOS)
    if ! command -v curl > /dev/null; then
        warn "curl est absent : MinUnit n'est pas téléchargé."
        return 1
    fi
    curl -fsSL -o "${DEFAULT_PROJECT_PATH}/${DEFAULT_HEADER_PATH}/minunit.h" "$url/minunit.h" &&
    curl -fsSL -o "${DEFAULT_PROJECT_PATH}/etc/minunit_example.c" "$url/minunit_example.c" ||
        warn "Le téléchargement de MinUnit a échoué (connexion ?)."
}

# Validates the project path input.
# Checks if the input is not empty and does not contain invalid characters.
# This function is used to ensure that the provided project path is suitable 
# for directory creation and does not cause any issues in the filesystem.
#
# Arguments:
#   $1 - The project path to validate.
#
# Returns:
#   0 if the project path is valid.
#   1 if the project path is invalid (either empty or contains special characters).
#
# Usage:
#   validate_project_path "example_project"
function validate_project_path() {
    if [[ -z "$1" ]]; then
        warn "Entrée invalide : le nom du projet ne peut être vide."
        return 1
    elif [[ $1 =~ [^a-zA-Z0-9_-] ]]; then
        warn "Entrée invalide : le nom du projet contient des caractères spéciaux."
        return 1
    fi
    return 0
}

# Interactive function to create a new C project.
# Prompts the user for the project name and initializes the project structure.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
# Arguments:
#   None
# Usage:
#   create_project
function create_project() {
   echo "Entrer le nom du nouveau projet :"
   read -r DEFAULT_PROJECT_PATH
   if ! validate_project_path "$DEFAULT_PROJECT_PATH"; then
       return 1
   fi
   initialize_rep
   if [ "$?" == 0 ] 
   then
      create_README
      create_main
      customize_makefile
      create_Makefile
      create_Doxyfile
      copy_minunit
      echo "Projet $(basename "$DEFAULT_PROJECT_PATH") créé."
   fi
}

# Opens an existing project or creates it if it doesn't exist.
# Prompts the user for the project name.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
# Arguments:
#   None
# Usage:
#   open_project
function open_project() {
   echo "Entrer le nom du projet à ouvrir :"
   read -r DEFAULT_PROJECT_PATH
   # Only a simple name: never ".", "..", or a path such as ~/Documents
   if ! validate_project_path "$DEFAULT_PROJECT_PATH"; then
      DEFAULT_PROJECT_PATH=""
      return 1
   fi
   if [ ! -e "$DEFAULT_PROJECT_PATH" ] 
   then
      echo "Projet inexistant. Il va être créé."
      initialize_rep
      if [ "$?" == 0 ] 
      then
         create_README
         create_main
         customize_makefile
         create_Makefile
         create_Doxyfile
         copy_minunit
      fi
      echo "Projet $(basename "$DEFAULT_PROJECT_PATH") créé."
      return 0
   else 
      if [ ! -d "$DEFAULT_PROJECT_PATH" ] 
      then 
         echo "Un fichier porte déjà ce nom."
         DEFAULT_PROJECT_PATH=""
         return 10
      else
         echo "Projet ouvert."        
      fi
fi
}

# Creates a compressed archive of the current project.
# The archive name includes authors' names and current date.
# Globals:
#   DEFAULT_PROJECT_PATH, AUTHOR1, AUTHOR2
# Arguments:
#   None
# Usage:
#   create_archive
function create_archive() {
   author1=$( echo "$AUTHOR1" | cut -f2 -d' ' )
   author2=$( echo "$AUTHOR2" | cut -f2 -d' ' )
   currentdate=$( date +%d-%m-%Y-%H-%M )

   if [ -n "$DEFAULT_PROJECT_PATH" ]; then
      cd "${DEFAULT_PROJECT_PATH}" || return ; make distclean; cd .. ;   
      tar czf "$DEFAULT_PROJECT_PATH-$author1-$author2-$currentdate.tgz" "$(basename "$DEFAULT_PROJECT_PATH")"
   else
      error "Projet courant inexistant !" "create_archive()"
   fi
   echo "Archive du projet courant créée."
}

# Deletes the current project directory and its contents.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
# Arguments:
#   None
# Usage:
#   suppress_project
function suppress_project() {
   if [ -z "$DEFAULT_PROJECT_PATH" ]; then
      echo "Aucun projet ouvert."
      return 1
   fi
   read -r -p "Supprimer définitivement le dossier $DEFAULT_PROJECT_PATH ? [o/N] " reponse
   if [ "$reponse" != o ] && [ "$reponse" != O ]; then
      echo "Suppression annulée."
      return 0
   fi
   rm -R -f -- "$DEFAULT_PROJECT_PATH" && DEFAULT_PROJECT_PATH="" && echo "Projet courant supprimé."
}

# Compiles the current C project using the Makefile.
# Globals:
#   DEFAULT_PROJECT_PATH - The path of the project directory.
# Arguments:
#   None
# Usage:
#   compile_project
function compile_project() {
   if [ -z "$DEFAULT_PROJECT_PATH" ]
   then
      echo "Aucun projet ouvert."
      return 12
   fi
   cd "${DEFAULT_PROJECT_PATH}" || return ; make ; cd .. ; 
   echo "Projet compilé."
}

# Main menu function.
# Displays the menu options and processes user input.
# The user can select options to create, open, archive, or delete projects.
function menu() {
   clear ; loop=y
   while [ $loop = y ]
   do
      echo "Générateur de squelette d'un projet C"  
      echo "====================================="
      echo "N|n : créer un nouveau projet"
      echo "O|o : ouvrir un projet"
      echo "S|s : supprimer le projet courant"
      echo "C|c : compiler le projet courant"
      echo "A|a : archiver le projet courant"
      echo "Q|q : quitter"
      echo
      read -r -s choix || choix=q # silent mode with no echo; end of input: quit
      case $choix in
         N|n) create_project ;;
         O|o) open_project ;;
         S|s) suppress_project ;;
         C|c) compile_project ;;
         A|a) create_archive ;;
         Q|q) loop=n ;;
           *) echo "Choix invalide !" ;;
      esac
      echo
   done 
}

# Checks dependancies on the system.
# Arguments:
#   None
# Usage:
#   check_dependencies
function check_dependencies() {
    local dependencies=("${DEFAULT_CC}" "doxygen" "make" "tar" "curl")
    local missing_deps=()

    for dep in "${dependencies[@]}"; do
        if ! command -v "$dep" &> /dev/null; then
            echo "Checking $dep: Not Found"
            missing_deps+=("$dep")
        else
            echo "Checking $dep: Found"
        fi
    done

    if [ ${#missing_deps[@]} -ne 0 ]; then
        error "Dépendances manquantes : ${missing_deps[*]}. Installez ces dépendances pour continuer."
    fi
}

#
# Beginning of the script
#
if [ "$#" -gt 1 ]; then
    error "Usage incorrect. Seule l'option '-h' est acceptée."
    exit 1
fi

if [ "$1" = "-h" ]; then
    help
fi

#check_dependencies
menu

exit 0