Anonymous Anonymous - 1 year ago 49
Bash Question

How to execute a file that is located in $PATH

I am trying to execute a

hallo_word.sh
that is stored at
~/bin
from this script that is stored at my
~/Desktop
. I have made both scripts executable. But all the time I get the problem message. Any ideas?

#!/bin/sh

clear
dir="$PATH"
read -p "which file you want to execute" fl
echo ""
for fl in $dir
do
if [ -x "$fl" ]
then
echo "executing=====>"
./$fl
else
echo "Problem"
fi
done

Answer

This line has two problems:

for fl in $dir
  1. $PATH is colon separated, but for expects whitespace separated values. You can change that by setting the IFS variable. This changes the FIELD SEPARATOR used by tools like for and awk.

  2. $fl contains the name of the file you want to execute, but you overwrite its value with the contents of $dir.

Fixed:

#!/bin/sh

clear
read -p "which file you want to execute" file
echo
IFS=:
for dir in $PATH ; do  
    if [ -x "$dir/$file" ]
    then
        echo "executing $dir/$file"
        exec "$dir/$file"
    fi
done
echo "Problem"