Hamid's blog

Linux Hints: 2. Be more Effective at Terminal with Bash Brace Expansion

May 10, 2020

shell command:

du -sh ~/code/git{hub,lab}

** What does it do?** Return folder size of ~/code/github and ~/code/gitlab folders in a human readable format.

description:

  • du -sh

    • return folder size in a human readable format for given path.
  • ~/code/git{hub,lab}

    • path to my folers
    • has few parts:

      • ~/code/git the fixed string part of path
      • {hub,lab} embraced part of string that will is a expand and be concatenated to previous part.





** Following two commands will generate exactly the same results as aforementioned command:**

    du -sh  ~/code/{github,gitlab}

and

    echo ~/code/git{hub,lab} | xargs du -sh

Further points

  • spaces are note allowed inside brace, otherwise it won't expand. If your folder name has space, enclosed it in quotes.

    • incorrect:

         echo {hub, lab}
      
    • correct:

         echo {hub,lab}
      
  • it is a better idea to use printf "%s\n" instead of echo:
           printf "%s\n" {hub,lab}