'why invoking "ls" (and "grep") in bash scipt depends on order of execution?

couldn't find and understand why I'm getting an error depending on the order of execution in my bash script.

I'm getting 2 arguments:

  1. path to a directory.
  2. a string.
PATH="$1"
WORD="$2"
FILES="$(ls ./testRoot/*.c)"

outputs that "ls: command not found".

but,

FILES="$(ls ./testRoot/*.c)"
PATH="$1"
WORD="$2"

works just fine.

I can't figure out why this is happening and wants to understand, and how can I handle this.

p.s the same goes for the 'grep' command, but I'm guessing it's the same reason.

Thanks.



Solution 1:[1]

PATH is a special Linux variable which contains all directories where to look for executable binaries, which is usually something like this:

echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

When you override this variable in your script, executables are not found anymore.

To solve this, simply use a variable name different from PATH.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 carlfriedrich