0

How could I call the $PATH variable in a subshell, such that I get the result I would in the normal shell?

[ec2-user@ip-172-31-45-160 ~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/ec2-user/.local/bin:/home/ec2-user/bin

That's my $PATH variable in the normal shell, but when I call this variable in a shell script, I get:

/sbin:/bin:/usr/sbin:/usr/bin

My goal was to make a script that automatically adds itself to the user's bin path (of course checking if the file already exists so as to not replace it and break something), and for that, I needed that shell's $PATH variable to be accessed within the script.

This is my full script. There are a lot of artifacts from earlier tries and tests, so please, don't bother with them:

#!/bin/bash

# This script will try to add itself to the user's path after being executed the first time

FILENAME=$(basename $0)
# echo $FILENAME

PATHVARS=$(echo $PATH)
NRPATHS=$(echo $PATHVARS | awk -F ':' '{print NF}')
# echo "$PATHVARS $NRPATHS"

echo $PATH
PATHLIST=$(echo $PATH | tr ':' ' ')
echo $PATHLIST

for word in $PATHLIST; do
#       echo "$word ---------------"
        if [[ -e "${word}/${FILENAME}" ]]; then
                echo "File ${word}/${FILENAME} already exists!"
        else
#               echo "Self copy successful: ${word}/${FILENAME}"
                cp -f ${FILENAME} ${word}/${FILENAME}
        fi
done
  • 2
    You're trying to add the script to every directory in the user's PATH? That's crazy. – glenn jackman Aug 30 '18 at 15:31
  • 1
    If you want just the user's bin dir, use "$HOME/bin" – glenn jackman Aug 30 '18 at 15:32
  • How do you run the script? When you run a script from a shell, the script automatically inherits the shell PATH. You have nothing to do. Are you not running the script using a shell? Are you using cron? sudo? (I bet on sudo) – andcoz Aug 30 '18 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.