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
#!/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 languagesecho"Listing my favorite programming languages:"forlanguageinJavaCPythonScalaCamlR;doecho"I like $language"sleep1# Pausing for 1 second between each iteration for demonstration purposesdoneecho"Loop completed."
#!/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 numberssum=0# Initialize the accumulatorecho"Adding numbers from 1 to 6:"foriin123456;dosum=$((sum+i))# Accumulate the sumecho"After adding $i, sum is: $sum"doneecho"Final sum: $sum"
#!/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=0LIST=""forfilein*;doif[-f"$file"];then# Check if it's a regular filename=${file%%.*}# before the first dotextension=${file##*.}# after the last dotecho"$name -> $extension"LIST="$LIST$file"count=$((count+1))# counted here: a name may contain spacesfidoneecho"List of files: $LIST"echoecho"Number of files: $count"
#!/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 definitiondisplay_message(){localmessage=$1# Using a parameter within the functionecho"We are in the display_message function."echo"Message: $message"echo"Now we exit the function."return0# Indicate successful execution}# Function call with a parameterecho"Calling the display_message function..."display_message"Hello from the function!"# Check the return status of the functionif[$?-eq0];thenecho"Function executed successfully."elseecho"Function execution failed."fi
#!/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 Bashless_simple(){localJUST_A_SECOND=$1# Sleep duration as a parameterlocalcounter=0localREPETITIONS=$2# Number of repetitions as a parameterecho"And now we run..."while["$counter"-lt"$REPETITIONS"];doecho"<------- FUNCTIONS are useful (${counter}) ------>"sleep"$JUST_A_SECOND"counter=$((counter+1))# Increment counterdone}# Call the function with parameters: sleep duration and number of repetitionsless_simple120
#!/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 numberecho-n"Enter a positive number: "read-rnumber
if![[$number=~^[0-9]+$]];thenecho"A positive integer is expected.">&2exit1fisum=0i=1# Calculate the sumwhile["$i"-le"$number"];dosum=$((sum+i))i=$((i+1))doneecho"The sum from 1 to $number is: $sum"
#!/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 loopclear
continue_loop="y"while["$continue_loop"="y"];doecho"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 moderead-s-rchoix
echo# Process user choicecase"$choix"in[Dd])date;;[Uu])who;;[Ww])pwd;;[Qq])continue_loop="n";;*)echo"Not a valid choice! Try again.";;esacechoread-r-p"Press any key to continue..."-n1-s
clear
doneecho"Exiting the menu. Goodbye!"
#!/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 languageslanguages=("C""C++""Java""Scala""Python")# Iterate over the array and print each languageecho"List of programming languages:"forlanguagein"${languages[@]}";doecho"Language: $language"done# Add a new language to the arrayecho"Adding 'Rust' to the list of programming languages..."languages+=("Rust")# Print the updated arrayecho"Updated list of programming languages:"forlanguagein"${languages[@]}";doecho"Language: $language"done# Demonstrating other array operationsecho"The first language in the list is: ${languages[0]}"# Accessing the first elementecho"The list of languages contains ${#languages[@]} elements."# Number of elements in the array
#!/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 Vimif[$#-le1];thenecho"Usage: $0 <word> <file1> [<file2> ...]"exit1fiword=$1shiftecho"Searching for files containing the word '$word'..."while[$#-gt0];doif[-f"$1"]&&[-r"$1"]&&grep-q-F-w--"${word}""$1";thenvim"$1"elseecho"Word '$word' not found or file '$1' cannot be read."fishiftdone
#!/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 substitutionecho"Bonjour à vous !"# Separate strings are concatenated with a space in betweenecho"Bonjour""à""vous""!"# Single quotes prevent variable expansion and command substitutionecho'Bonjour à vous !'# Without quotes, the string is subject to word splitting and globbingechoBonjouràvous!
# Escaped double quotes are treated as part of the stringecho\"Bonjouràvous!\"# Escaped single quotes are treated as part of the stringecho\'Bonjouràvous!\'
#!/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.ifrm-f--./*~;thenecho"Temporary files are removed!"fi
#!/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 contentsMESSAGE="Bonjour"message="bonjour"nom="Jean"PI="3.14159"# Use . for decimal pointecho"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"
#!/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 expandedBAD="great"UNIX="Unix is a $BAD system!"echo"$UNIX"# Output: Unix is a great system!echo""# Single quotes: Variables are treated as literal stringsBAD="terrible"WINDOWS='Ms-Windows is a $BAD system!'echo"$WINDOWS"# Output: Ms-Windows is a $BAD system!# Demonstrating escaped charactersecho"Using double quotes with escaped characters: \$BAD"echo'Using single quotes with escaped characters: \$BAD'# Demonstrating command substitutionecho"Command substitution with double quotes: $(date)"echo'Command substitution with single quotes: $(date)'
#!/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-rfilename# -r: a backslash in the name is kept as isif[!-e"${filename}"];thenecho"${filename}: no such file.">&2exit1fiifrm-i--"${filename}";thenecho"File have been removed."elseecho"File removal was cancelled or failed."fi
#!/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 substitutionCOMMAND1=`ls`echo"Listing files using backticks:"echo"$COMMAND1"echo""# It is recommended to use $(...) for command substitution due to better readability and nesting abilityecho"It can also be done using \$(...):"COMMAND2=$(ls)echo"$COMMAND2"# Example of nested command substitutionecho""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=$(lsnon_existent_directory);thenecho"Failed to execute command (COMMAND4 is empty: '$COMMAND4')"fi
#!/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 commandecho"Remove backup files on the desktop"# The substitution $(...) is only used to know whether there are filesbackup_files=$(find~/Desktop/-name"*.*~")if[-z"$backup_files"];thenecho"No backup files found."elseecho"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"*.*~"-execrm-i-v{}\;fi
#!/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 backupecho"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[$#-ne1];thenecho"Usage: $0 DIRECTORY">&2exit1fiSOURCE_DIR="$1"if[-d"$SOURCE_DIR"];thenecho"Creating a tarball backup of $SOURCE_DIR"iftar-czf"${BACKUP}""$SOURCE_DIR";thenecho"Backup successfully created at ${BACKUP}"elseecho"Failed to create backup."fielseecho"Source directory $SOURCE_DIR does not exist. Backup not created."fi
#!/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 operationsecho"Using let for arithmetic:"letx=8*2+3
echo"Let x = 8 * 2 + 3, x = $x"lety=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 operationsecho"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 $((...))
#!/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 operationsecho-n"Enter the first number: ";read-rx
echo-n"Enter the second number: ";read-ry
# Integers only (an optional minus sign, then digits)if![[$x=~^-?[0-9]+$&&$y=~^-?[0-9]+$]];thenecho"Integers are expected.">&2exit1fiif["$y"-eq0];thenecho"Division by zero: the second number must not be 0.">&2exit1fi# Inside $(( )), variables can be written without $sum=$((x+y))difference=$((x-y))product=$((x*y))ratio=$((x/y))remainder=$((x%y))# Displaying resultsecho"Sum: $sum"echo"Difference: $difference"echo"Product: $product"echo"Ratio: $ratio"echo"Remainder: $remainder"
#!/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 statementsecho-n"Enter your username: "read-rusername
if[[-z"$username"]];thenecho"No username entered. Please try again."exit1fiif[["$username"=="$USER"]];thenecho"Hello, $username. How do you feel today?"elseecho"You are not $USER! Who are you, $username?"fi
#!/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 operationsecho-n"Enter an integer value x such as: 1 < x < 10 : "read-rx
# Stop at once if the input is not an integer (otherwise: "integer expression expected")if![[$x=~^-?[0-9]+$]];thenecho"Bad choice! '$x' is not an integer.">&2exit1fiif["$x"-lt10]thenif["$x"-gt1]thenecho"$x*$x=$((x*x))"elseecho"Bad choice! The number must be higher than 1."fielseecho"Bad choice! The number must be lower than 10."fi
#!/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 rangeecho-n"Enter an integer value x such as: 1 < x < 10 : "read-rx
# Stop at once if the input is not an integer (otherwise: "integer expression expected")if![[$x=~^-?[0-9]+$]];thenecho"Bad choice! '$x' is not an integer.">&2exit1fi# Check if the integer is in the range 1 < x < 10if[["$x"-gt1&&"$x"-lt10]];thenecho"$x*$x=$((x*x))"elseecho"Bad choice! The number must be strictly between 1 and 10."fi
#!/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-rx
# Stop at once if the input is not an integer (otherwise: "integer expression expected")if![[$x=~^-?[0-9]+$]];thenecho"Bad choice! '$x' is not an integer.">&2exit1fiif((x>1&&x<10));thenecho"$x*$x=$((x*x))"elseecho"Bad choice! The number must be strictly between 1 and 10."fi
#!/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 expressionecho-n"Enter an integer value x such as: 1 < x < 10 : "read-rx
# Stop at once if the input is not an integer (otherwise: "integer expression expected")if![[$x=~^-?[0-9]+$]];thenecho"Bad choice! '$x' is not an integer.">&2exit1fiif["$x"-gt1]&&["$x"-lt10]thenecho"$x*$x=$((x*x))"elseecho"Bad choice! The number must be strictly between 1 and 10."fi
#!/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 directoryif[$#-eq1];thenfile_to_move="$1"# Check if the file existsif[!-f"$file_to_move"];thenecho"Error: File '$file_to_move' not found."exit1fi# Create the trash directory if it doesn't existif[!-dtrash];thenmkdirtrash||{echo"Failed to create trash directory";exit1;}fi# Move the file to the trash directory with confirmationmv-i-v"$file_to_move"trash
elseecho"Usage: $0 <filename>"echo"Example: $0 document.txt"exit1fi
#!/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 matchingecho-n"Enter an integer value x such as: 1 < x < 10 : "read-rx
echo"Checking the value of x using case statement:"case$xin[2-9])echo"x = $x";;*)echo"Bad choice! The number must be between 2 and 9.";;esac
#!/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 fileLOG_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.functionerror(){echo"Error in function $2: $1!"|tee-a"$LOG_FILE">&2exit1}# 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.functionwarn(){echo"Erreur : $1"|tee-a"$LOG_FILE">&2}# Displays the help message for the script usage.# Arguments:# None# Usage:# helpfunctionhelp(){echo"$(basename"$0") est un script shell pour créer des projets C."exit0}# 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.functioninitialize_rep(){if[!-e"$DEFAULT_PROJECT_PATH"];thenif!mkdir"$DEFAULT_PROJECT_PATH";thenwarn"La création du dossier pour le projet a échoué."return1fifordirin"${DEFAULT_DIR_STRUCTURE[@]}";domkdir-p"$DEFAULT_PROJECT_PATH/$dir"touch"$DEFAULT_PROJECT_PATH/$dir/.gitkeep"donereturn0elsewarn"Le projet existe déjà"return1fi}# Creates a README.md file in the project directory.# Globals:# DEFAULT_PROJECT_PATH - The path of the project directory.# Arguments:# None# Usage:# create_READMEfunctioncreate_README(){cat>"$DEFAULT_PROJECT_PATH/README.md"<<EOF# Project $DEFAULT_PROJECT_PATH
## DescriptionAcompletedescriptionoftheproject...
## InstallationAcompletedescriptionofitsinstallation...
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