export /etc/environment variables to current environment; from a shell script? - bash

How do I bring environment variables from /etc/environment to the terminal and what it calls?
file0.bash
#!/usr/bin/env bash
bash ./file1.bash
echo $FOO_BAR
for line in $( sudo cat /etc/environment ); do export $line; done
file1.bash
#!/usr/bin/env bash
sudo sed -i '/^FOO_BAR/d' /etc/environment
printf FOO_BAR="$HOME/Foo\n" | sudo tee -a /etc/environment
for line in $( sudo cat /etc/environment ); do export $line; done
Console
$ echo $FOO_BAR
$ bash file0.bash
[sudo] password for myusername:
FOO_BAR=/home/myusername/Foo
$ echo $FOO_BAR
$ # What I want to avoid is having to revert to this:
$ for line in $( sudo cat /etc/environment ); do export $line; done
$ echo $FOO_BAR
/home/myusername/Foo

When you execute a script as:
bash ./file.bash
OR else:
./file1.bash
Running a shell script like this launches a new process, a subshell.
All the variables created in a subshell are not visible outside the block of code in the subshell. They are not accessible to the parent process, to the shell that launched the subshell. These are, in effect, variables local to the child process. Note that exporting variables also won't make them available in the parent shell. That just makes them available to further subshells of the running subshell.
To change this behavior you can force script to execute in current shell itself using any of these 2 way:
source ./file1.bash
OR
. ./file1.bash

Related

Saving the result of an echo command in a shell script?

I am attempting to store the result of an echo command as a variable to be used in a shell script. Debian 4.19.0-6-amd64
The command works in terminal: echo $HOSTNAME returns debian-base, the correct hostname.
I attempt to run it in a shell script, such as:
#!/usr/bin/bash
CURRENT_HOSTNAME=`echo $HOSTNAME`
echo $CURRENT_HOSTNAME
I have tried expansion:
CURRENT_HOSTNAME=$(echo $HOSTNAME)
And just to cover some more bases, I tried things like:
CURRENT_HOSTNAME=$HOSTNAME
# or
CURRENT_HOSTNAME="$HOSTNAME"
# also, in case a problem with reserved names:
test=$HOSTNAME
test="$HOSTNAME"
Works great in the terminal! Output is as follows:
root#debian-base:/scripts# echo $HOSTNAME
debian-base
root#debian-base:/scripts# TEST_HOSTNAME=$HOSTNAME
root#debian-base:/scripts# echo $TEST_HOSTNAME
debian-base
root#debian-base:/scripts# TEST_TWO_HOSTNAME=$(echo $HOSTNAME)
root#debian-base:/scripts# echo $TEST_TWO_HOSTNAME
debian-base
As soon as I run the script (as above):
root#debian-base:/scripts# sh test.sh
root#debian-base:/scripts#
What am I doing wrong?
You are using bash as your terminal. Bash has the variable $HOSTNAME set. You run your script with sh. sh does not have a $HOSTNAME.
Options:
bash test.sh
Or run it as a program:
chmod +x test.sh
./test.sh
But I think you need to change your first line to:
#!/bin/bash
As I don't think bash is installed in /usr/bin in most cases. But you need to try. To figure out where bash is installed use which bash
Another option is to use the hostname binary:
CURRENT_HOSTNAME=$(hostname)
echo $CURRENT_HOSTNAME
Which works in both bash and sh.
You can start sh by just running sh. You will see it has a bash-like terminal. You can try to do echo $HOSTNAME. It will not show, because it's not there. You can use set to see all the variables that are there (as sh does not have tab completion it's harder to figure out).

Bash: exported variable not loaded in sh script

I have the following test.sh script:
#!/bin/sh
echo "MY_VARIABLE=$MY_VARIABLE"
Well, if I execute the following:
export MY_VARIABLE=SOMEVALUE
/bin/bash test.sh
it prints:
MY_VARIABLE=
Why the MY_VARIABLE is not read in the test.sh script?
You can reproduce the context here using the following script:
touch test.sh
chmod a+x test.sh
echo "#!/bin/sh" >> test.sh
echo "echo "MY_VARIABLE=$MY_VARIABLE"" >> test.sh
export MY_VARIABLE=something
/bin/bash test.sh
In your script to create the context, the line
echo "echo "MY_VARIABLE=$MY_VARIABLE"" >> test.sh
creates the following line in test.sh:
echo MY_VARIABLE=
if MY_VARIABLE was unset before. The expansion of $MY_VARIABLE is done in the shell that prepares your context.
If you use single quotes
echo 'echo "MY_VARIABLE=$MY_VARIABLE"' >> test.sh
the script test.sh contains the correct line
echo "MY_VARIABLE=$MY_VARIABLE"
and prints MY_VARIABLE=something as expected.
Everything works well but if you want your parent process to keep environment update, you must source your script:
source test.sh
Otherwise, changes will only have effect during the execution of your script.
You can consider it the same as sourcing your ~/.bashrc file.

bash: parse_git_branch: command not found

This should be very simple.
I recently noticed that when I type 'bash' into Terminal on Mac it shows this:
Jays-MacBook-Pro: ~ $ bash
bash: parse_git_branch: command not found
When before it didn't. Can someone explain why and how to resolve.
It is likely that you configured BASH to run parse_git_branch and print the result as part of PS1 (or alike). You can check this by: "echo $PS1" and "echo $PROMPT_COMMAND".
However, parse_git_branch is not a builtin function of bash. Below is how I configured my PS1. You may want to copy my git_branch_4_ps1 as your parse_git_branch
PS1='\n' # begin with a newline
PS1=$PS1'\[\e[38;5;101m\]\! \t ' # time and command history number
PS1=$PS1'\[\e[38;5;106m\]\u#\h ' # user#host
PS1=$PS1'\[\e[7;35m\]${MY_WARN}\[\e[0m\] ' # warning message if there is any
PS1=$PS1'\[\e[38;5;10m\]${MY_EXTRA} ' # extra info if there is any
PS1=$PS1'\[\e[0;36m\]$(git_branch_4_ps1) ' # git_branch_4_ps1 defined below
PS1=$PS1'\[\e[38;5;33m\]\w' # working directory
PS1=$PS1'\n\[\e[32m\]\$ ' # "$"/"#" sign on a new line
PS1=$PS1'\[\e[0m\]' # restore to default color
function git_branch_4_ps1 { # get git branch of pwd
local branch="$(git branch 2>/dev/null | grep "\*" | colrm 1 2)"
if [ -n "$branch" ]; then
echo "(git: $branch)"
fi
}
If your parse_git_branch is defined in ~/.bash_profile, it will not be loaded when you open a non-login shell (e.g. by running bash).
The differences between login and non-login shells are described here: Difference between Login Shell and Non-Login Shell? For our purposes, the main difference is that login shells (e.g. that when you first open Terminal) automatically source ~/.bash_profile upon startup, whereas non-login shells (e.g. that when you run bash from within Terminal) do not.
To fix this error, simply source your ~/.bash_profile after running bash:
user#host:~ $ bash
bash: parse_git_branch: command not found
user#host:~ $ source .bash_profile
Alternatively, place the function in ~/.bashrc instead, which will be automatically sourced by non-login shells (as covered in the earlier link).
Instead of having
parse_git_branch
call in PS1 definition alone you may use
parse_git_branch 2>/dev/null
to send stderr to /dev/null. This will silence the error you don't want to see.
have you export your $PS1 ?
You can check by run command:
printenv
else you should export it by run:
export -n PS1
after you will can run sudo or sudo su without problem
The key to this is to NOT export PS1. If it's exported, then any non-login shell also takes PS1. Since .bash_profile is automatically source'd by the login shell, the PS1 variable only affects the login shell.

Why my command of bash shell is not working?

I add environment value in ~/.profile
export TEST1="abc"
I execute bash shell script go.sh
#!/bin/bash
source ~/.profile
but result of go.sh is not working.(can't find TEST1 variable).
set | grep TEST1
Otherwise when I execute go.sh in command line, it working. (can find TEST1)
Why go.sh is not working?
When you execute your script, a new process is created with its own environment. When you get the prompt back, that script is finished, and you cannot access its variables.
You have to source your script:
source go.sh
If all you want is a shortcut for reading the profile, use an alias:
alias go='source ~/.profile'
A script cannot affect the environment of its parent shell.
You can see the changes if you include the test in the script:
#!/bin/bash
source ~/.profile
set | grep TEST1
Or when you perform the source ... in your current shell
$ source ~/.profile
$ set | grep TEST1
the command
set|grep TEST
should works even without $
If you're using bash, try to put your variable in .bashrc
in any case if you try to set the variable via command line it should works too.
bash-3.2$ export TEST1="abc"
bash-3.2$ set | grep TEST1
TEST1=abc
_=TEST1
bash-3.2$ set | grep $TEST1
TEST1=abc
bash-3.2$ echo $TEST1
abc
bash-3.2$

Can I export a variable to the environment from a Bash script without sourcing it?

Suppose that I have this script:
export.bash:
#! /usr/bin/env bash
export VAR="HELLO, VARIABLE"
When I execute the script and try to access to the $VAR, I don't get any value!
echo $VAR
Is there a way to access the $VAR by just executing export.bash without sourcing it?
Is there any way to access to the $VAR by just executing export.bash without sourcing it ?
Quick answer: No.
But there are several possible workarounds.
The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:
$ cat set-vars1.sh
export FOO=BAR
$ . set-vars1.sh
$ echo $FOO
BAR
Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:
$ cat set-vars2.sh
#!/bin/bash
echo export FOO=BAR
$ eval "$(./set-vars2.sh)"
$ echo "$FOO"
BAR
A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:
$ cat set-vars3.sh
#!/bin/bash
export FOO=BAR
exec "$#"
$ ./set-vars3.sh printenv | grep FOO
FOO=BAR
This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).
In order to export out the VAR variable first, the most logical and seemly working way is to source the variable:
. ./export.bash
or
source ./export.bash
Now when echoing from the main shell, it works:
echo $VAR
HELLO, VARIABLE
We will now reset VAR:
export VAR=""
echo $VAR
Now we will execute a script to source the variable then unset it:
./test-export.sh
HELLO, VARIABLE
--
.
The code: file test-export.sh
#!/bin/bash
# Source env variable
source ./export.bash
# echo out the variable in test script
echo $VAR
# unset the variable
unset VAR
# echo a few dotted lines
echo "---"
# now return VAR which is blank
echo $VAR
Here is one way:
Please note: The exports are limited to the script that execute the exports in your main console - so as far as a cron job I would add it like the console like below... for the command part still questionable: here is how you would run in from your shell:
On your command prompt (so long as the export.bash file has multiple echo values)
IFS=$'\n'; for entries in $(./export.bash); do export $entries; done; ./v1.sh
HELLO THERE
HI THERE
File cat v1.sh
#!/bin/bash
echo $VAR
echo $VAR1
Now so long as this is for your usage - you could make the variables available for your scripts at any time by doing a Bash alias like this:
myvars ./v1.sh
HELLO THERE
HI THERE
echo $VAR
.
Add this to your .bashrc file:
function myvars() {
IFS=$'\n';
for entries in $(./export.bash); do export $entries; done;
"$#";
for entries in $(./export.bash); do variable=$(echo $entries|awk -F"=" '{print $1}'); unset $variable;
done
}
Source your .bashrc file and you can do like the above any time...
Anyhow back to the rest of it...
This has made it available globally then executed the script...
Simply echo it out and run export on the echo!
File export.bash
#!/bin/bash
echo "VAR=HELLO THERE"
Now within script or your console run:
export "$(./export.bash)"
Try:
echo $VAR
HELLO THERE
Multiple values so long as you know what you are expecting in another script using the above method:
File export.bash
#!/bin/bash
echo "VAR=HELLO THERE"
echo "VAR1=HI THERE"
File test-export.sh
#!/bin/bash
IFS=$'\n'
for entries in $(./export.bash); do
export $entries
done
echo "round 1"
echo $VAR
echo $VAR1
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
unset $variable
done
echo "round 2"
echo $VAR
echo $VAR1
Now the results
./test-export.sh
round 1
HELLO THERE
HI THERE
round 2
.
And the final final update to auto assign, read the VARIABLES:
./test-export.sh
Round 0 - Export out then find variable name -
Set current variable to the variable exported then echo its value
$VAR has value of HELLO THERE
$VAR1 has value of HI THERE
round 1 - we know what was exported and we will echo out known variables
HELLO THERE
HI THERE
Round 2 - We will just return the variable names and unset them
round 3 - Now we get nothing back
The script:
File test-export.sh
#!/bin/bash
IFS=$'\n'
echo "Round 0 - Export out then find variable name - "
echo "Set current variable to the variable exported then echo its value"
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
export $entries
eval current_variable=\$$variable
echo "\$$variable has value of $current_variable"
done
echo "round 1 - we know what was exported and we will echo out known variables"
echo $VAR
echo $VAR1
echo "Round 2 - We will just return the variable names and unset them "
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
unset $variable
done
echo "round 3 - Now we get nothing back"
echo $VAR
echo $VAR1
Execute
set -o allexport
Any variables you source from a file after this will be exported in your shell.
source conf-file
When you're done execute. This will disable allexport mode.
set +o allexport
I found an interesting and neat way to export environment variables from a file:
In file env.vars:
foo=test
Test script:
eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # =>
export eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
# a better one. "--" stops processing options,
# key=value list given as parameters
export -- `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
Another workaround that, depends on the case, it could be useful: creating another bash script that inherits the exported variable. It is a particular case of Keith Thompson's answer, will all of those drawbacks.
File export.bash:
# !/bin/bash
export VAR="HELLO, VARIABLE"
bash
Now:
./export.bash
echo $VAR
The answer is no, but for me I did the following
The script:
myExport
#! \bin\bash
export $1
An alias in my .bashrc file:
alias myExport='source myExport'
Still you source it, but maybe in this way it is more useable and it is interesting for someone else.
Maybe you can add a function in ~/.zshrc or ~/.bashrc.
# set my env
[ -s ~/.env ] && export MYENV=`cat ~/.env`
function myenv() { [[ -s ~/.env ]] && echo $argv > ~/.env && export MYENV=$argv }
Because of the use of a variable outside, you can avoid the use of a script file.
Export environment variables using script file
Problem:
When you run a script, it executes in a child shell and returns back to the parent shell after execution. Exporting variables only works down the child shells, you can't export a child shell's variable back to the parent shell.
Solution:
From your script file invoke a child shell along with variables that you want to export, this will create a new child shell with your variables exported.
script.sh ->
bash -c 'export VAR=variable; exec bash'
: : CIPH3R
I don't think this can be done, but I found a workaround using alias. It will only work when you place your script in your scripts directory. Otherwise your alias will have an invalid name.
The only point to the workaround is to be able to have a function inside a file with the same name and not have to bother sourcing it before using it. Add the following code to file ~/.bashrc:
alias myFunction='unalias myFunction && . myFunction && myFunction "$#"'
You can now call myFunction without sourcing it first.
This workaround is somehow hinted to elsewhere, but maybe not that clearly:
In your script, after setting the variable, start a new shell, rather than return.
My use cases is that I have a number of terminals open and in some of them I want some values for some variables, while in others I want other values.
As using source may be harder to remember, a small advantage of this approach is when it takes a while to realize that you forgot to use source, and you have to start from scratch.
(For me it makes more sense to use source script, as the missing variables are noticed immediately.)
I had similar problem calling ssh-agent -s in a script called by option -e in rsync.
In the script eval $(ssh-agent -s) don't preserve the environment variables for the next call.
rsync -e 'source ssh-check-agent.sh -p 8022' does not work, so I made a workaround. In the script I saved the variables in a temporal file after call ssh-agent like:
echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK;" > /tmp/ssh-check-agent.vars
echo "export SSH_AGENT_PID=$SSH_AGENT_PID;" >> /tmp/ssh-check-agent.vars
and after in the script that calls rsync (backup.sh) I call:
source /tmp/ssh-check-agent.vars
The problem is that script that calls rsync must be called by source (source backup.sh).
I know that is not the question (I use two times source), but I put here if someone has similar problem with rsync.
simple naive approach that works:
script 1:
echo "something" > /tmp/myvar
script 2:
myvar=$(cat /tmp/myvar)
If you want to set a variable for the calling shell there is a robust approach using c unix sockets.
The result will be tested like this:
$ ./a.out &
[1] 5363
$ ./b.out 123;a=`./b.out`;echo ${a}
123
[1]+ Done ./a.out
See a.c, b.c, and a.h from my github.

Resources