• [^] # Re: quelques pistes

    Posté par . En réponse au message SCRIPT SHELL. Évalué à 4. Dernière modification le 03 janvier 2020 à 11:42.

    Hello.

    Ce qui est bien en shell c'est que tu peux tester ...

    [totof@droopyfb ~]$ cd /tmp
    [totof@droopyfb /tmp]$ mkdir test1
    [totof@droopyfb /tmp]$ cd test1
    [totof@droopyfb /tmp/test1]$ mkdir dir1 dir2 dir3
    [totof@droopyfb /tmp/test1]$ touch file1 file2 file3
    [totof@droopyfb /tmp/test1]$ touch dir1/file1 dir2/file2 dir3/file3
    [totof@droopyfb /tmp/test1]$ for directory in */ ; do
    > echo $d
    > done

    Tu n'obtiens pas ce que tu veux ....

    Tandis qu'avec ça, c'est déjà mieux :

    [totof@droopyfb /tmp/test1]$ for directory in */
    > do
    > echo $directory
    > done
    dir1/
    dir2/
    dir3/

    Quand tu écris for <variable> in <expression>, tu demande au shell d'évaluer l'expression (qui est censé te retourner une liste de mots séparée par défaut par un ou plusieurs espaces ou une tabulation), puis de splitter cet liste chaine en utilisant le fameux séparateur, et de boucler sur chaque élément. La variable est une variable de boucle qui contiendra chaque élément de ta chaine tour a tour.

    Exemple :

    [totof@droopyfb /tmp/test1]$ for i in a b c
    > do
    > echo $i
    > done
    a
    b
    c
    

    Extrait de la page de man :

     Word Splitting
     The shell scans the results of parameter expansion, command
     substitution, and arithmetic expansion that did not occur within double
     quotes for word splitting.
     The shell treats each character of IFS as a delimiter, and splits the
     results of the other expansions into words using these characters as
     field terminators. If IFS is unset, or its value is exactly
     <space><tab><newline>, the default, then sequences of <space>, <tab>,
     and <newline> at the beginning and end of the results of the previous
     expansions are ignored, and any sequence of IFS characters not at the
     beginning or end serves to delimit words. If IFS has a value other
     than the default, then sequences of the whitespace characters space,
     tab, and newline are ignored at the beginning and end of the word, as
     long as the whitespace character is in the value of IFS (an IFS
     whitespace character). Any character in IFS that is not IFS
     whitespace, along with any adjacent IFS whitespace characters, delimits
     a field. A sequence of IFS whitespace characters is also treated as a
     delimiter. If the value of IFS is null, no word splitting occurs.