2

I wanted to write a script on my Ubuntu to show all the executable files in all of the directories in the $PATH variable. Here is my script:

#!/bin/bash
IFS=:
for dir in $PATH;do
        echo $dir:
        for files in $dir/*;do
                b=$(basename $files)
                [ -x "$b" ] && echo $"    $b" 
        done
done 

but the output is

/usr/local/sbin:
/usr/local/bin:
/usr/sbin:
/usr/bin:
/sbin:
/bin:
/usr/games:
/usr/local/games:
/snap/bin:
/home/sudin/programming/shell:
      brightness
      for
      ifthen
      loop
      mat2
      myfind
      searchex

Why aren't the executable files of other directories listed?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
joe
  • 25

1 Answers1

4

With

[ -x "$b" ]

you’re testing if the file with the name stored in $b, without a path, is executable; so the script will only find entries on the PATH which happen to match an executable in the current directory.

Testing the full path will fix this:

[ -x "$files" ] && printf "    %s\n" "$b"

While we’re at it, let’s fix the quoting:

#!/bin/bash
IFS=:
for dir in $PATH;do
        printf "%s:\n" "$dir"
        for files in "$dir"/*;do
                b="$(basename "$files")"
                [ -x "$files" ] && printf "    %s\n" "$b"
        done
done

See List all commands that a shell knows for a more comprehensive solution, which deals with empty entries in PATH, malformed entries which contain globs, and directories.

Stephen Kitt
  • 434,908