0

I'm trying to create a bash script that will let me augment the path everytime I execute it. Here is the code I have to point towards where I'm going:

#!/bin/bash
#script to augment path
echo "what directories do you want to add:"
read MYNEWPATH
echo "adding the "$MYNEWPATH" directory to PATH"
export PATH
echo "your new env variable is now:"
echo $PATH
exit 0

when i run it and cmd asks for a new directory, I enter the directory i want to add but it says "line 6: PATH: command not found"

Open for all suggestions, thanks in advance.

  • 1
    Line 6? Is that `export PATH`? Are you sure you don't have a line `PATH = "$PATH:$MYNEWPATH"` in there? In any case, [no you can't do this](https://stackoverflow.com/questions/1464253/global-environment-variables-in-a-shell-script) – that other guy Sep 10 '18 at 21:45
  • 1
    This seems like a lot of effort to just do: `PATH+="/new/path/1:/new/path/2"` – glenn jackman Sep 10 '18 at 23:14

1 Answers1

0

You'll need to append the new variable to the old path (line 4), like so:

export PATH=$MYNEWPATH:$PATH

But, when you run a script, BASH fires off a new child process and the altered PATH variable reverts once the script is finished running. To handle this you can use the script to create a sourcefile and then source it so that the new path persists in the parent shell environment.

#!/bin/bash
echo "enter new path: "
read MYNEWPATH
echo export PATH=$MYNEWPATH:$PATH > sourcefile

After you have run the script, a new file is created that you can source into the parent shell. All you have to do from there is source sourcefile and your new, altered path exists in your current environment.

You'll most likely want to tweak the code so that the sourcefile is created in a specific spot. You can then use an alias to automate the process further.

You might also find this of some help: how to alter path within a shell script

casey
  • 41
  • 5
  • 1
    Instead of invoking a script and then sourcing a file, you can just make this script into a function: `pathadd() { PATH+=:$1; printf "%s\n" "New path:" "$PATH"; }; pathadd /foo/bar` – glenn jackman Sep 10 '18 at 23:17