1

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.

AllForCode
  • 49
  • 5
  • Rule of a thumb: use lowercase variables. `FILES="$(ls ./testRoot/*.c)"` Do not parse ls. Use bash array. `files=( ./testRoot/*.c )` – KamilCuk Apr 08 '22 at 12:40
  • See [Correct Bash and shell script variable capitalization](https://stackoverflow.com/q/673055/4154375), [Bash Pitfalls #1 (for f in $(ls *.mp3))](https://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29), and [Why you shouldn't parse the output of ls(1)](http://mywiki.wooledge.org/ParsingLs). – pjh Apr 08 '22 at 12:47
  • Thanks, everyone, no more caps for shell script variables that's for sure. – AllForCode Apr 13 '22 at 13:08

1 Answers1

3

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.

carlfriedrich
  • 2,919
  • 1
  • 15
  • 29
  • That is a rookie mistake... didn't even think about it. Thanks! – AllForCode Apr 08 '22 at 12:36
  • 1
    @AllForCode There are a whole bunch of all-caps variable names with special functions or meanings, so it's best to use lower- or mixed-case names for your own things (i.e. anytime you *don't* want a special function or meaning). – Gordon Davisson Apr 08 '22 at 18:30