Good day to all

I have a script that uses certain folders that need to be saved in order not to re-enter each time it is run, or to enter it, but only when necessary.

# Сохраняем проект в глобальный массив для использования автоматически function projectSave() { if [ ! -z $PROJECT ]; then echo "Please write a project name!" read PROJECTNAME export PROJECT=$PROJECTNAME else echo "your project is $PROJECT" fi } projectSave exit 1 

The code above exports the variable to the path, but there, as I understand it, the hierarchy, and this variable is not visible a second time. What to do? Tell me who knows.

  • The code above does not export to the path, but to the list of variables. What is the hierarchy there and what do you want next? Pass this path to another script? Pass as parameter. - Smithson
  • I want to run the same script, read it again in another method, if it is empty, call this method - jcmax
  • It is not that simple. Variables are inherited from top to bottom, from your script they will be available only to scripts called from your script. If the script is called later from the shell, then the variable should export the shell. - Smithson
  • I don’t quite understand what a new environment is meant for every time, and all variables that are exported are entered there or you just need to specify the path to the folder or file where this variable lies. I have only one script and one variable and I want to use it N number of times in order not to enter the name of the project I need each time. - jcmax
  • Yes, each time the script is invoked, a new environment is created that is a copy of the current environment and the called script cannot change the environment of the calling process. - avp

1 answer 1

You can use the file to save variables. and read from it with the source command.


for your example:

  1. Add a line like this before calling the projectSave function:

     [ -r savedvars ] && source savedvars 
  2. and in the function text, after receiving the variable value from the user, add, for example, the following line:

     echo "export PROJECT=$PROJECTNAME" > savedvars 

and between calls to your program, the value of the variable will be stored in the savedvars file in the current directory (both the name and the location of the file are at your complete discretion).