Outils pour utilisateurs

Outils du site


issue177:c_c

Most of us don’t think twice when typing at a terminal, it’s just there. What is actually happening is that you are typing commands into a shell that is interpreting your commands. By default, Ubuntu ships with bash, but you can install another if you like. I will focus on bash. The reason being, that if you ever get to use servers or containers on the internet, chances are good that it is bash. A lot of time I hear, it is difficult to learn shell scripting. Sure, bash is not the friendliest of syntaxes, but sometimes you just need a question answered and a small shell script will do. The question may be something arbitrary like: Do I have any money? If you are a wage serf like me, the only time you have money is when you have been paid. So to simplify the question, I might ask, have I been paid? Now that is a yes or no question, the kind the computer likes. Yes or no questions translate easily into true or false. There is a dilemma in this question, as the computer has no access to my bank account and therefore has no idea if I have been paid. However, I can do the next best thing, check if it is ‘payday’. The computer has no idea what ‘payday’ is, but we do, it is on the 27th of each month. We have a target and a yes or no question, so we can write a simple script.

La plupart d'entre nous ne réfléchissent pas à deux fois lorsqu'ils tapent sur un terminal, il existe, c'est tout. Ce qui se passe en fait, c'est que vous tapez des commandes dans un shell qui interprète vos commandes. Par défaut, Ubuntu est livré avec bash, mais vous pouvez en installer un autre si vous le souhaitez. Je vais me concentrer sur bash, parce que, si vous avez l'occasion d'utiliser des serveurs ou des conteneurs sur Internet, il y a de fortes chances que ce soit bash.

J'entends souvent dire qu'il est difficile d'apprendre à faire des scripts shell. Bien sûr, bash n'est pas la plus conviviale des syntaxes, mais parfois vous avez juste besoin de répondre à une question et un petit script shell fera l'affaire. La question peut être quelque chose d'arbitraire comme : Ai-je de l'argent ? Si vous êtes un serf salarié comme moi, le seul moment où vous avez de l'argent est lorsque vous avez été payé. Donc, pour simplifier la question, je pourrais demander : est-ce que j'ai été payé ? Voilà une question à laquelle on répond par oui ou par non, le genre de question que l'ordinateur apprécie. Les questions par oui ou par non se traduisent facilement par vrai ou faux. Il y a un dilemme dans cette question, car l'ordinateur n'a pas accès à mon compte bancaire et ne sait donc pas si j'ai été payé. Cependant, une manière alternative de résoudre ce problème est de vérifier si c'est le jour de la paie. L'ordinateur n'a aucune idée de ce qu'est un « jour de paie », mais nous le savons, c'est le 27 de chaque mois. Nous avons un objectif et une question à laquelle il faut répondre par oui ou par non, ce qui nous permet d'écrire un script simple.

Open those terminals and let's have some silly fun. Type: nano gotmoney.sh and press enter. As you know, all shell scripts require a path to the shell. So we start off by adding: #!/bin/bash -to the header of our script. We can use bash’s if-statement to ask the question; “If today is the 27th … TRUE or FALSE” then we got paid or did not get paid” The if statement in bash does this nifty trick of opening with the word “if” and closing with “fi” (the reverse). The way it works is, IF TRUE, then do something, else do nothing. So this is our outline, we now need to formulate the question. Here is where you need to think about what you want. Remember, garbage in, garbage out. Let’s open another terminal or tab and test out our ‘question’. This is important, if your command does not work in bash, it will not work in your script.

Ouvrez ces terminaux et amusons-nous bêtement. Tapez :

nano gotmoney.sh

et appuyez sur Entrée.

Comme vous le savez, tous les scripts shell nécessitent un chemin vers le shell. Nous commençons donc par ajouter : #!/bin/bash -à l'en-tête de notre script. Nous pouvons utiliser l'instruction if de bash pour poser la question : « Si aujourd'hui est le 27 … VRAI ou FAUX » alors nous avons été payés ou nous n'avons pas été payés. L'instruction if de bash s'ouvre astucieusement avec le mot « if » et se ferme avec « fi » (l'inverse). Son fonctionnement est le suivant : SI VRAI, alors faites quelque chose, sinon ne faites rien.

Voici donc notre schéma, nous devons maintenant formuler la question. C'est ici que vous devez réfléchir à ce que vous voulez. Rappelez-vous ; mal ficelé au début, mal ficelé la fin (« GIGO, garbage in, garbage out »).

Ouvrons un autre terminal ou onglet et testons notre « question ». C'est important, si votre commande ne fonctionne pas dans bash, elle ne fonctionnera pas dans votre script.

First, let’s see what the switches are, type: man date and press enter. Going down a bit you will see - “FORMAT controls the output.” After all, I am only interested in the day, as I get paid on the 27th , every month and therefore the month and the hours and seconds are of no use to me. If you don’t understand what I am talking about, simply type: date and press enter. According to the man page, “%d” is what I am looking for as it represents the day. Let’s test that out, type: date %d and press enter. What happened? You did not pay attention to the Synopsis part; it says, “+FORMAT”. Now try: date +%d and press enter. Great, now we have something that works. Last issue we learned about the $ variable. Now it’s time to use it. So… if some condition is true -do something. (The technical description of an if statement, hehe) Clear this tab or second terminal and type: if [ $(date +%d) -eq 27 ] ; then echo “Quick, spend some before the wife sees it!!”; fi and press enter What happened? Well unless today was the 27th , you would get no output. Remember, if the condition is FALSE, nothing happens. (Else is not part of this discussion) Let us dissect that query: IF [ TRUE ]; then blah…

Tout d'abord, voyons ce que sont les commutateurs, tapez : man date et appuyez sur entrée. En descendant un peu, vous verrez - « FORMAT controls the output. » (Le FORMAT contrôle la sortie).

Après tout, je ne suis intéressé que par le jour, car je suis payé le 27 de chaque mois et donc le mois, les heures et les secondes ne me sont d'aucune utilité. Si vous ne comprenez pas ce dont je parle, tapez simplement : date et appuyez sur la touche Entrée.

Selon la page du manuel, « %d » est ce que je recherche car il représente le jour. Testons cela, tapez : date %d et appuyez sur entrée. Que s'est-il passé ? Vous n'avez pas prêté attention à la partie Synopsis ; il est écrit « +FORMAT ». Essayez maintenant : date +%d et appuyez sur la touche Entrée. Super, maintenant nous avons quelque chose qui fonctionne. Dans le dernier numéro, nous avons appris à connaître la variable $. Il est maintenant temps de l'utiliser. Donc… si une condition est vraie, faites quelque chose. (La description technique d'une instruction if, héhé.)

Effacez cet onglet ou le second terminal et tapez : if [ $(date +%d) -eq 27 ] ; then echo “Vite, dépensez-en avant que votre femme ne le voie !!”; fi puis appuyez sur Entrée.

Que s'est-il passé ? Eh bien, à moins qu'aujourd'hui soit le 27, vous n'obtiendrez aucun résultat. Rappelez-vous, si la condition est FALSE, rien ne se passe. (Else ne fait pas partie de cette présentation).

Décortiquons cette requête : IF [ TRUE ]; then blah…

The [ TRUE ] part is then broken into a question to determine true or false. If our variable “date +%d” (it is in brackets as it is not one word) -eq (equal to) 27. We have -eq as our comparison operator like -gt for ‘greater than’ and -lt for ‘less than’. You learned these in school, so you should know them by now. If you are unsure, see: https://tldp.org/LDP/abs/html/comparison-ops.html Also remember the spaces with the square brackets as they are commands. “[ “ and “[[ “ (we will get to these much further down the line when we get to test) Before anyone comments, I am not a code monkey, this reads easier for me than all the unnecessary white space. Save it and set the script executable. (You should know that much by now) Just to test the validity, try changing the 27 to today’s date and see if the echo fires. Congratulations! You wrote a script! You can put this into cron and have it fire once a day. That way when it is ‘payday’, you will get a friendly reminder! Cron is beyond the scope of this article, but we will visit it in the future. Did I make a mistake? misc@fulcirclemagazine.org

La partie [ TRUE ] est ensuite décomposée en une question pour déterminer si elle est vraie ou fausse. Si notre variable « date +%d » (elle est entre parenthèses car il ne s'agit pas d'un mot) -eq (est égale à) 27. Nous utilisons -eq comme opérateur de comparaison, comme -gt pour « plus grand que » et -lt pour « moins grand que ». Vous les avez appris à l'école ; vous devriez donc les connaître maintenant. Si vous n'êtes pas sûr, consultez : https://tldp.org/LDP/abs/html/comparison-ops.html

N'oubliez pas non plus les espaces entre crochets, car il s'agit de commandes. « [ » et « [[ » (nous y reviendrons plus tard, lorsque nous aborderons les tests).

Avant que quelqu'un ne fasse des commentaires, je ne suis pas un singe codeur, cela se lit plus facilement pour moi que tous les espaces blancs inutiles.

Sauvegardez-le et rendez le script exécutable. (Vous devriez savoir comment faire maintenant.)

Juste pour tester sa validité, essayez de changer le 27 en date d'aujourd'hui et voyez si l'écho se déclenche.

Félicitations ! Vous avez écrit un script ! Vous pouvez le mettre dans cron et le faire déclencher une fois par jour. Ainsi, lorsque le jour de la paie arrive, vous recevrez un rappel amical !

L'utilisation de cron dépasse le cadre de cet article, mais nous y reviendrons dans le futur.

Ai-je fait une erreur ? misc@fulcirclemagazine.org

issue177/c_c.txt · Dernière modification : 2022/02/01 16:03 de andre_domenech