Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

for j in * .* ; do 
    cp $j ../$name-S$i.gid/${j%%. * }$i.${j#*.}
done

Could someone tell me what this for loop does? What do *, % and # mean? ($name is a path of a directory in which there are -S1.gid ... -Sn.gid directory)

share|improve this question

marked as duplicate by jasonwryan, slm, strugee, Braiam, Thomas Nyman May 5 at 3:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
It is generally better to quote $j (i.e. "$j") and the rest. If a file name contains whitespace then the unquoted command breaks. –  Hauke Laging May 4 at 23:16

1 Answer 1

  • It loops (for foo in bar; do something; done) over the files matching the * and .* globs and
    • copies (cp)
      • each file ($j) to
      • a path composed of
        • the parent directory (../)
        • followed by a directory path
          • starting with the value of $name,
          • followed by -S,
          • some other unknown variable ($i)
          • and finally .gid/,
        • then a file name starting with
          • the string remaining after removing from the end of the file (${j...}) the longest string (%%) matching the glob . *, meaning
            • a dot
            • followed by a space,
            • followed by any number of characters
            • followed by a space
          • followed by the value of $i,
          • followed by a dot
          • and finally the string remaining after removing from the start of the file (${j...}) the shortest string matching the glob *., meaning
            • any number of characters
            • followed by a dot.

All this is explained in man bash. This code should be simplified to use quoted variables for each of those expansions to explain what they are. It's not maintainable as is IMO.

share|improve this answer
    
Holy nested lists batman! –  Patrick May 4 at 23:13
    
Yeah, that's what you get with one-liners. They look tidy until you have to actually read them. –  l0b0 May 4 at 23:15
    
@l0b0 - impressive use of nested lists 8-) –  slm May 4 at 23:37
    
Um, thanks. It just seemed the easiest way to explain that messy one-liner. –  l0b0 May 4 at 23:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.