1

I create a temporary directory in a.sh TEMP_DIR=$(mktemp -d), and I would like to access this temporary directory from b.sh. I have already tried exporting(Can I export a variable to the environment from a bash script without sourcing it?) and sourcing the path to this directory, but they are not useful for my case, because the two scripts are separated from each other by several commands and I cannot directly run b.sh from a.sh.

How can I achieve this?

Marc
  • 588
  • 2
  • 15
  • Does this answer your question? [Where to create temp files when access to /tmp/ is denied?](https://stackoverflow.com/questions/172552/where-to-create-temp-files-when-access-to-tmp-is-denied) – Masood Mar 30 '21 at 09:47

3 Answers3

1

If you have no way of passing a parameter to the different parts of your project (not even through the environment), I only see two options:

  1. if you're architecture doesn't allow you to pass parameters, but you need that feature, revise the architecture
  2. if you cannot revise the architecture, use a global well-known name. Instead of random name, use a fixed name within /tmp, and take the necessary precautions to protect against common problems such as multiples instances of your scripts using this directory simultaneously.
Volker Stolz
  • 7,274
  • 1
  • 32
  • 50
1

I would create the temporary directory from the top level script (the one calling a.sh then b.sh) then put the path either in an environment variable MY_TEMP_DIR or an argument to the a.sh and b.sh scripts.

This is much cleaner because it is for the top level script to also take care of the removal of the temporary directory.

If you cannot modify the top level script then you have to make a.sh and b.sh communicate, one way or another. A simple way would be to have the a.sh script create the temporary directory and place its path into a file that both a.sh and b.sh know and can read from.

ant1g
  • 969
  • 9
  • 13
1

If b.sh is not a child process of the process running a.sh, you could write to inside a.sh the name of the directory to a file and read the name of the directory from that file in b.sh.

If however a.sh and b.sh share a common parent process somewhere up in the process tree, you could consider deciding the name of the temporary directory inside that parent process and setting an environment variable with this name, which is then used by both of your scripts.

To avoid conflicts in the naming of this directory, you could use your PID as part of the name.

user1934428
  • 19,864
  • 7
  • 42
  • 87