简体   繁体   中英

Augmenting path on Linux using bash script

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM