Skip to content
Extraits de code Groupes Projets
Valider bb4acc51 rédigé par Pierre-Yves Barriat's avatar Pierre-Yves Barriat
Parcourir les fichiers

Revision 2024

parent ad0791b8
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
......@@ -18,7 +18,7 @@ https://forge.uclouvain.be/barriat/learning-bash
![h:200](assets/bash_logo.png)
##### October 17, 2023
##### October 10, 2024
###### CISM/CÉCI Training Sessions
......@@ -257,6 +257,8 @@ Consider `string=abcABC123ABCabc` and `filename=myfile.txt`
* `${string#a*C}` is `123ABCabc`
* `${filename##myfile}` is `.txt`
<!-- WARNING -->
---
* substring removal from back :
......@@ -270,6 +272,8 @@ Consider `string=abcABC123ABCabc` and `filename=myfile.txt`
* `${variable+default}` :
if `variable` is unset or null, nothing is substituted, otherwise the expansion of `default` is substituted
<!-- WARNING -->
---
# Arithmetic
......@@ -354,12 +358,9 @@ The following operaors can be used beween conditions:
# Conditional exemple
(Don't pay too much attention to the details yet)
```bash
#!/bin/bash
echo "Please enter a number: "
read num
num=6
if [ $num -gt 5 ] && [ $num -le 7 ]
then
......@@ -371,8 +372,6 @@ else
fi
```
Read the **standard input stream** with the `read` command
---
| Operator | Description |
......@@ -413,8 +412,7 @@ Use the double brackets just like we did for variables :
```bash
#!/bin/bash
echo "Please enter a number: "
read num
num=6
if (( $num % 2 == 0 ))
then
......@@ -422,6 +420,7 @@ then
fi
```
<!--
---
### Case Statements
......@@ -447,6 +446,7 @@ case $space_free in
;;
esac
```
-->
---
......@@ -454,10 +454,12 @@ esac
1. In your `bash_exercises` folder create a new bash file called `exercise_2.sh` and make it executable
2. Ask the user for two numbers smaller or equal to 100, put them in variables `NUMBER1` and `NUMBER2`
> `read NUMBER1`
> `read NUMBER2`
3. Do the following only if the numbers are smaller than 100
4. Check if at least one of the numbers is a multiple of 3, and tell the user
5. Otherwise, check if both numbers are even, and tell the user
6. If the user's numbers ar too big, tell them
4. Otherwise, check if both numbers are even, and tell the user
5. If the user's numbers ar too big, tell them
> `echo 'message'`
---
......@@ -481,6 +483,8 @@ echo ${my_array[2]}
echo ${my_array[@]}
```
<!--
---
### Associative arrays = Dictionaries (Bash 4.0 or higher)
......@@ -551,14 +555,6 @@ Basic loop structures in Bash scripting :
# Basic while loop
counter=0
while [ $counter -lt 3 ]; do
let counter+=1
echo $counter
done
```
```bash
# Basic until loop
counter=1
until [ $counter -gt 10 ]; do
echo $counter
((counter++))
done
......@@ -588,8 +584,10 @@ for file in $path/*.f90
for i in $( cat file.txt )
```
<!--
![bg right 85%](./assets/select_example.png)
---
```bash
......@@ -607,6 +605,7 @@ do
echo "Key is '$key' => Value is '${fruits[$key]}'"
done
```
-->
---
......@@ -616,10 +615,9 @@ Speed game:
1. Use the following website to get a list of random words: https://randomwordgenerator.com and put them together in a variable
2. Register the start time with `date +%s` and put it in a variable `TSTART`
3. Loop over the words and ask the user to give the number of letters. Put the answers in an associative array using the words as keys and the answers as values
3. Loop over the words and ask the user to give the number of letters. Echo the answers.
4. Register the end time in `TEND`
5. Display the total run time
6. Loop over the associative array to compute the score (number of good answers) and show it to the user
5. Display the total run time and the score.
---
......@@ -661,6 +659,8 @@ a b c d e
---
<!--
### Flags
```bash
......@@ -684,6 +684,8 @@ bash test_arg.sh -f 'John Smith' -a 25 -u john
---
-->
# Input/Output streams
Shells use 3 standard I/O streams
......@@ -804,6 +806,13 @@ _files="$@"
---
# Hands-on exercise
<!-- Repartir de l'exercise précédent. Stocker les résultatst dans un fichier au lieu de stdin.
Puis; lire ce fichier pour compter le score. -->
---
# Functions
* "small script within a script" that you may call multiple times
......@@ -904,24 +913,18 @@ print_something () {
print_something Mars
```
## Be careful in case of "overriding commands"
```bash
#!/bin/bash
ls () {
command ls -lh # 'command' keyword prevents ambiguity
}
ls
```
> Be careful in case of "overriding commands": plaese never use an existing linux command name.
---
# Hands-on exercise
1. Write a script called `exercise_3.sh` expecting **2 arguments**. If not exactly two arguments are provided, exit with an error and show a "usage" message to the user.
1. Write a script called `exercise_4.sh` expecting **2 arguments**. If not exactly two arguments are provided, exit with an error and show a "usage" message to the user.
2. Write a function taking a **folder path** and an **extension** as arguments and giving the list of matching files to the user
3. Imagine you are running jobs taking data from two folders, each with a dedicated extension. Use the two arguments of the script as the name of the two folders and **get the two lists of files**.
4. Since your work needs to read these files, **check that all files can be read**. If some files cannot be read, display their name to the user
<!-- 3. Imagine you are running jobs taking data from two folders, each with a dedicated extension. Use the two arguments of the script as the name of the two folders and **get the two lists of files**.
4. Since your work needs to read these files, **check that all files can be read**. If some files cannot be read, display their name to the user-->
<!-- Créer un petit exercice raisonnable-->
---
......@@ -1022,6 +1025,45 @@ greeting $COUNTRY
---
# Debug
Tips and techniques for debugging and troubleshooting Bash scripts
### use `set -x`
enables debugging mode : print each command that it executes to the terminal, preceded by a `+`
### check the exit code
```bash
#!/bin/bash
if [ $? -ne 0 ]; then
echo "Error occurred"
fi
```
---
### use `echo`
"classical" but useful technique : insert `echo` throughout your code
```bash
#!/bin/bash
echo "Value of variable x is: $x"
```
### use `set -e`
this option will cause Bash to exit with an error if any command in the script fails
---
Thank you for your attention<!--fit-->
===
---
### Running parallel processes in subshells
Processes may execute in parallel within different subshells
......@@ -1069,41 +1111,4 @@ time ./manager_seq.sh
time ./manager_par.sh
```
---
# Debug
Tips and techniques for debugging and troubleshooting Bash scripts
### use `set -x`
enables debugging mode : print each command that it executes to the terminal, preceded by a `+`
### check the exit code
```bash
#!/bin/bash
if [ $? -ne 0 ]; then
echo "Error occurred"
fi
```
---
### use `echo`
"classical" but useful technique : insert `echo` throughout your code
```bash
#!/bin/bash
echo "Value of variable x is: $x"
```
### use `set -e`
this option will cause Bash to exit with an error if any command in the script fails
---
Thank you for your attention<!--fit-->
===
\ No newline at end of file
---
\ No newline at end of file
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter