Search code examples
linuxbashshellunix

Bash: Creating a shell variable in a bash script that I can access from command line


I have very little experience working with bash. With that being said I need to create a bash script that takes your current directory path and saves it to a shell variable. I then need to be able to type "echo $shellvariable" and have that output the directory that I saved to that variable in the bash script. This is what I have so far.

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

now when I go to command line and type "echo $mypath" it outputs nothing.


Solution

  • You have to export the variable for it to exist in the newly-execed shell:

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