1

When I echo $PATH in a terminal window, it outputs:

/home/charles/anaconda3/bin:
/home/charles/anaconda3/condabin:
/usr/local/sbin:/usr/local/bin:
/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
/usr/local/games:/snap/bin:/snap/bin:
/home/charles/.emacs.d/bin

But when I run the script (not as root):

#!/bin/sh
echo $PATH

it only outputs the root paths, not the ones from my home directory:

/usr/local/sbin:/usr/local/bin:
/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
/usr/local/games:/snap/bin:/snap/bin

I'm trying to launch spyder from a script, which comes from:

$ which spyder
/home/charles/anaconda3/bin/spyder

Is there some way to make the script recognize the parts of the path from my home directory?

Solved: I moved the code adding emacs and anaconda to the path from ~/.bashrc to ~/.profile.

  • Related: https://unix.stackexchange.com/q/26047/237982. Specifically Gilles answer that talks about how to correct set your PATH variable. Sounds like you may be setting it in your rc file instead of your profile file. – jesse_b Jun 01 '22 at 14:39
  • In which file do you add the directories `/home/charles/...` to your `PATH`? What is the first line of your script? (= Is the script run by `bash` or by `sh`?) Please [edit] your question to provide this information, don't use comments for this purpose. – Bodo Jun 01 '22 at 14:46
  • Welcome, can we assume that you are not running the script as root? – schrodingerscatcuriosity Jun 01 '22 at 14:46

1 Answers1

0

Your script runs in a subshell - meaning that it was spawned by your interactive/login shell. A subshell is a shell spawned for the express purpose of running your script/program. One of the rules for a subshell is that it can access the global variables set by the "parent shell", but not the local variables.

This suggests that the /home/... variables are local variables, meaning that you set them somewhere/somehow - maybe in ~/.bashrc?

The solution is that you must declare your local PATH variables inside your script. You could do this as follows:

export PATH="$PATH:/home/charles/anaconda3/bin:/home/charles/anaconda3/condabin:/home/charles/.emacs.d/bin"

This PATH is now local to your script/subshell, and will not be propagated as a global variable.

Seamus
  • 2,522
  • 1
  • 16
  • 31
  • 1
    Redoing your PATH in every individual script would get annoying fast. Far better to set the PATH somewhere like `.bash_profile` that will be sourced by the login shell and use `export` so it gets passed on to all forked shells (or there may be other options depending on login manager, init system or choice of shell). – frabjous Jun 02 '22 at 00:46
  • @frabjous: Good point. I didn't put that in my answer as the OP asked about a specific script, not all scripts. Sometimes, a de-scoped PATH is a *good thing*. :) – Seamus Jun 02 '22 at 01:04