How can I set a shell variable in a Bash script and access it later from the command line?

I’m new to Bash scripting, and I’m trying to figure out how to create a script that stores the current directory path in a variable and lets me access that variable later in the terminal.

Here’s what I’ve tried:

#!/bin/bash mypath=$(pwd) cd $1 echo $mypath exec bash

The script prints the path as expected, but when I go back to the command line and type echo $mypath, it’s empty. How can I bash set a variable in a script so that it persists and is accessible in the current shell session?

Is this even possible, or do I need to use source or some other method to make it work?

Been scripting with Bash for years, here’s a classic gotcha that trips folks up. When you run something like ./myscript.sh, it opens in a new subshell, so any bash set variable command won’t affect your current terminal.

Want those variables to stick around? Use source:

source myscript.sh  
# or shorthand  
. myscript.sh  

This runs it in the current shell, so mypath=$(pwd) inside your script will persist* after it ends. Simple but powerful!

Totally agree with @tim-khorev sourcing works great. But here’s a cleaner way I use when I don’t want to source the whole script. I just make the script output the value and then capture it like this:

mypath=$(./getpath.sh)  

Inside getpath.sh:

#!/bin/bash  
echo $(pwd)  

This way, bash set variable becomes super predictable, great for CI pipelines or quick automation. You stay in control of what gets set, and your script stays focused. :wrench:

Yup, and if you’re handling multiple environment vars dynamically, here’s a trick I’ve picked up after managing some complex setups. Have your script echo out export statements and then eval them:

myscript.sh:

#!/bin/bash  
echo "export mypath=\"$(pwd)\""  

Then run:

eval $(./myscript.sh)  

Now your bash set variable actually updates your current shell, perfect when you need to generate dynamic config on the fly. Not the most beginner-friendly, but incredibly useful. :rocket: