Bash variable available for use outside loop

In the below for loop , I extract a variable $d which is an id that will change each time. The bash executes the problem that I am having is that p (after the done ) is the path with the extracted $d . However, I can not use it in subsequent loops as it is not reconized. I have been trying to change the code so that I can use p in other loops but can not seem to. I added comments as well. Thank you :).

for f in /path/to/file/*.zip ; do
    echo "Start directory creation: $(date) - file: $f" >> "$d"/processing.log # log start
     bname=`basename $f` # strip of path
     d="$(echo $bname|cut -d_ -f1)" # remove after first underscore
     unzip $f -d /path/to/file/$d  # unzip folder
#rm -rf $file
      cp /path/to/file/$d/Variants/${d}_v1_${d}_RNA_v1/*full.tsv /path/to/file/ # copy full.tsv for analysis
      cp /path/to/file/$d/Variants/${d}_v1_${d}_RNA_v1/*Non-Filtered*.vcf /path/to/file/  # copy Non-Filtered.vcf for analysis
      mv /path/to/file/$d /path/to/file/
    echo "End directory creation: $(date) - file: $f" >> "$d"/processing.log # log end
done  # end loop
p=/path/to/file/$d  # store path in p
echo $p   # test output

I don't quite understand what you mean exactly but i assume on program rerun you wish to reuse $p from the previous run.
Try saving it as a source file and calling it at any time. I have used the '/tmp/' directory to store the sourcefile in this demo...

echo '#!/bin/bash' > /tmp/sourcefile
echo "p=${p}" >> /tmp/sourcefile

And source at anytime in any bash shell:

source /tmp/sourcefile

Example longhand: OSX 10.14.1, default bash terminal.

Last login: Thu Feb 21 20:10:56 on ttys000
AMIGA:amiga~> p="/usr/bin/local/"
AMIGA:amiga~> echo '#!/bin/bash' > /tmp/sourcefile
AMIGA:amiga~> echo "p=${p}" >> /tmp/sourcefile
AMIGA:amiga~> exit
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

Restart a terminal:

Last login: Thu Feb 21 20:17:07 on ttys000
AMIGA:amiga~> echo "$p"

AMIGA:amiga~> source /tmp/sourcefile
AMIGA:amiga~> echo "$p"
/usr/bin/local/
AMIGA:amiga~> exit
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

If this is not what you want then re-explain...
Hope this helps...

1 Like

There is nothing in the code above which would prevent $d from being available, so I suspect stripping your example down to the minimum has stripped out the problem, too. The usual gotcha is that assigning variables behind pipes doesn't work, i.e.

echo asdf | (
...
code block
...
D=1234
)

echo $D

the assignment happens in a subshell, not the outside shell

3 Likes

Thank you all :).