Issue
The following bash function defines two enviromental variable that are going to be used with the script test.sh located on the external usb.
quick_function(){
export curent_dir=$(pwd)
export ref_folder="${home}"
local quick_path=$(find /media/$USER -type f -name test.sh)
# run script located on the usb stick from the current directory
chmod +x "$quick_path"
"$quick_path"
}
with the aim to produce some test_dir within the current dir (and not on the usb stick, where the script.sh is located). This is test.sh
# the both input paths are commented since they have been already provided in the function defined in .bashrc
#curent_dir=$(pwd)
#ref_folder="${home}"
mkdir "$ref_folder"/test_dir
For the test purposes I uncomment the $curent_dir and $ref_folder defined in the test.st and (amazingly) found that the script called from the quick_function () still produces the test_dir in any place from which i opened the terminal (and never on the usb stick ... )
Does it means that for this example I do not need the both enviromental variables exported in the function, or alternatively these variables always overright the variables (with the same names) defined in the subsequently executed script from the same function ?
Solution
The export seem ok. I assume, the problem is with (export
)home=$(pwd)
. This looks as if you assumed the variable home
would contain the path to your home directory (e.g. /home/yourusername/
). However, pwd
prints the path to the current directory, so the location of the new directory will always be in your working directory.
Either way, you don't need the environment variables.
- To create the new directory inside your working directory, use
mkdir test_dir
- To create the new directory inside your home directory, use
mkdir ~/test_dir
ormkdir "$HOME/test_dir"
.
produces the test_dir in any place from which i opened the terminal (and never on the usb stick ... )
Sounds like you want to create the new directory on the USB stick, right next to test.sh
. In that case ...
- you could
export ref_folder="$(dirname "$quick_path")"
inside yourquick_function()
afterquick_path
was defined and beforetest.sh
was called - but it would be way easier to use
dirname
on$0
or$BASH_SOURCE
insidetest.sh
instead of manually handling thatref_folder
variable.
For the test purposes I uncomment the $home and $ref_folder defined in the test.st and found that the script called from the quick_function() still produces the test_dir in any place from which I opened the terminal
Because the definitions of these variables are the same.
Does it means [...] [exported] variables always overright the variables (with the same names) defined in the subsequently executed script from the same function ?
Its the other way around! The variables in the inner-most scope (test.sh) shadow the exported variables from the outer scopes (quick_function()).
Answered By - Socowi Answer Checked By - Willingham (WPSolving Volunteer)