Search code examples
linuxbashpath-variables

Get and print directories from $PATH in bash


The script that I have to write must find the directories from the $PATH variable and print only the ones that end with an i.

How am I thinking about doing it

  • Get each directory from the variable with a for loop.
  • Find the length of each directory and get the last character from each using a substring
  • Use an If condition to print the directories that end with an i

Problems

  • The directories are not separated with a new line and I can't read them using a for loop.

Any ideas on how to get over this problem,or can you think of something more appropriate.


Solution

  • You can use this BASH one-liner for that job:

    (IFS=':'; for i in $PATH; do [[ -d "$i" && $i =~ i$ ]] && echo "$i"; done)
    
    • IFS=':' sets input field separator to :
    • $PATH is iterated in a for loop
    • Each path element is tested if it is a directory and if it is ending with i using BASH regex
    • If test passes then it is pritned