简体   繁体   中英

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.

You can just run source <file_with_your_vars> , this will load your variables in yours script or command line session.

> cat source_vars.sh
my_var="value_of_my_var"
> echo $my_var

> source source_vars.sh
> echo $my_var
value_of_my_var

You have to export the variable for it to exist in the newly- exec ed shell:

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

Hello

'env -i' gives control what vars a shell/programm get...

#!/bin/bash
mypath=$(pwd)
cd $1
echo $mypath
env -i mypath=${mypath} exec bash

...ie with minimal environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM