Outils pour utilisateurs

Outils du site


linux:bash (lu 64218 fois)

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
Prochaine révision
Révision précédente
Prochaine révision Les deux révisions suivantes
linux:bash [12-03-2020 11:37]
edmc73 [Faire un prompt]
linux:bash [08-09-2020 16:28]
edmc73 [Exemple de condition]
Ligne 343: Ligne 343:
 </code> </code>
  
 +Tester le contenu d'une chaine avec du regex
  
 +Tester une date yyyymmdd de facon très simple
 +
 +<code bash>
 +[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"
 +</code>
 +
 +ou plus complet
 +
 +<code bash>
 +[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
 +#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
 +#                 ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
 +#                      |                                |
 +#                                        |              |
 +#           | --year--   --month--           --day--          |
 +#                    either 01...09      either 01..09     end of line
 +# start of line            or 10,11,12         or 10..29
 +#                                              or 30, 31
 +</code>
 +
 +That is, you can define a regex in Bash matching the format you want. This way you can do:
 +
 +<code bash>
 +[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"
 +</code>
 +where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.
 +
 +Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.
 +
 +In other shells you can use grep. If your shell is POSIX compliant, do
 +
 +<code bash>
 +(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"
 +</code>
 +In fish, which is not POSIX-compliant, you can do
 +
 +<code bash>
 +echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"
 +</code>
 ===== Boucle ===== ===== Boucle =====
  
Ligne 428: Ligne 468:
 select CHOIX in "${LISTE[@]}" ; do select CHOIX in "${LISTE[@]}" ; do
     case $REPLY in     case $REPLY in
-        1|y)+        yes|y)
         echo ok         echo ok
         break         break
         ;;         ;;
-        2|n)+        no|n)
         echo ko         echo ko
         break         break
         ;;         ;;
 +        *) echo "invalid option $REPLY";;
     esac     esac
 done done
linux/bash.txt · Dernière modification: 07-05-2023 20:38 de edmc73