Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
297
rated 0 times [  297] [ 0]  / answers: 1 / hits: 398005  / 2 Years ago, thu, november 25, 2021, 8:37:48

I have written the following script to set some environment variables when needed:


#!/bin/sh
export BASE=/home/develop/trees
echo $BASE
export PATH=$PATH:$BASE
echo $PATH

Below the command and the results I can see on my terminal: the script runs, but the variables are not set at the end.


~$: ./script.sh
/home/develop/trees
/bin:......:/home/develop/trees
~$: echo $BASE

~$:

What is wrong?


More From » bash

 Answers
0

export exports the variable assignment to child processes of the shell in which the export command was ran. Your command-line environment is the parent of the script's shell, so it does not see the variable assignment.



You can use the . (or source) bash command to execute the script commands in the current shell environment and achieve what you want, e.g.



source ./script.sh
echo "$BASE"


Will produce



/home/develop/trees


The source command, often seen in scripts, is a bash synonym for ., which is part of the POSIX standard (so . is available in dash, for example, but source isn't).



. ./script.sh     # identical to "source ./script.sh"


(. script.sh and source script.sh will first look for script.sh in PATH, so it's safer to specify the path to script.sh.)


[#44224] Saturday, November 27, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stantildlike

Total Points: 363
Total Questions: 135
Total Answers: 120

Location: Pitcairn Islands
Member since Fri, Dec 17, 2021
2 Years ago
;