0

So I have a function that I wish to run from my command line.

cat foo.sh

#!/bin/bash
echo foobar

I export it to my PATH variable and change to a different directory.

export PATH=${PATH}:/home/usr/scripts/foo.sh

mkdir test && cd test
sh foo.sh
sh: foo.sh: No such file or directory

If i run it like so foo.sh I get bash: foo.sh: command not found.

I could run it with the absolute path, but I didn't think I would need to if I added it to my $PATH. What mistake am I making here?

Thanks.

2
  • PATH should contain paths, not files i.e. PATH=${PATH}:/home/usr/scripts Commented Aug 17, 2021 at 16:24
  • Note that sh foo.sh in a different directory still won't work even if you fix the PATH, this tells sh to run the file foo.sh in the current directory.
    – DonHolgo
    Commented Aug 17, 2021 at 18:41

1 Answer 1

1

Several issues here. The $PATH consists of colon-separated directories, not files. You shouldn't declare a script as a bash script and then use sh to run it. Generally speaking, a file that you're going to call as if it were a standard utility wouldn't have an extension. (Extensions are optional in many situations anyway.)

# Create a directory
mkdir -p "$HOME/bin"

# Create a script in that directory
cat <<'EOF' >"$HOME/bin/myscript"    # Don't use "test" :-O
#!/bin/bash
echo This is myscript
EOF

# Make it executable
chmod a+x "$HOME/bin/myscript"

# Add the directory to the PATH
export PATH="$PATH:$HOME/bin"

# Now run the script as if it's a normal command
myscript

The caution against using a script called test is that /bin/test already exists as a valid command. Furthermore, in many shells test is a built-in that will override your own script regardless of the directory order in $PATH.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .