Environment variable not setting up after running bash script [duplicate] - linux

This question already has answers here:
Setting environment variable in shell script does not make it visible to the shell
(2 answers)
Closed 4 months ago.
I am writing a bash script to automate the task of setting environment variables for my project. but when I execute my bash script using sh env.sh (env.sh is my file name). I am able to get value from the AWS secret manager and when I do echo inside the bash script I am able to print the env variable but when I run the echo $variable after the bash file is executed then it returns nothing.
I tried replacing eval to source but no luck
also i searched on stackoverflow for the issue but none of them helped.
find the script below
#! /usr/bin/env bash
if [[ "$OSTYPE" == "darwin"* ]]; then
echo 'running'
if ! [ -x "$(command -v aws)" ]; then
echo 'Aws is not installed. Installing aws............................' >&2
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
if ! [ $(id -u) = 0 ]; then
echo "The script need to be run as root." >&2
exit 1
fi
sudo installer -pkg AWSCLIV2.pkg -target /
if ! [ -x "$(command -v aws)" ]; then
echo 'There was some issue installing aws cli. Install aws-cli manually and then run the script!!!' >&2
exit 1
fi
echo "Running aws command please enter the aws access key and secrect"
aws configure
fi
aws secretsmanager get-secret-value --secret-id abc --query SecretString --output text | jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' > /tmp/secrets.env
eval $(cat /tmp/secrets.env | sed 's/^/export /')
fi
I am currently running this bash file on Mac OS, but I would like it to operate on any OS.

If the file contained enviroment variable names setup_local_env.sh, Try
source setup_local_env.sh
This will add them to your current session.
There is another solution called dot source. Check the reference here
. ./setup_local_env.sh
The reason if you directly run ./setup_local_env.sh, it does not work, is because it creates a new bash process, and sets the environment variable there, and then it's lost once the new bash process exits.

Related

Can't run bash file inside ZSH

I've placed a bash file inside .zshrc and tried all different ways to run it every time I open a new terminal window or source .zshrc but no luck.
FYI: it was working fine on .bashrc
here is .zshrc script:
#Check if ampps is running
bash ~/ampps_runner.sh & disown
Different approach:
#Check if ampps is running
sh ~/ampps_runner.sh & disown
Another approach:
#Check if ampps is running
% ~/ampps_runner.sh & disown
All the above approaches didn't work (meaning it supposes to run an app named ampps but it doesn't in zsh.
Note: It was working fine before switching to zsh from bash. so it does not have permission or syntax problems.
Update: content of ampps_runner.sh
#! /usr/bin/env
echo "########################"
echo "Checking for ampps server to be running:"
check=$(pgrep -f "/usr/local/ampps" )
#[ -z "$check" ] && echo "Empty: Yes" || echo "Empty: No"
if [ -z "$check" ]; then
echo "It's not running!"
cd /usr/local/ampps
echo password | sudo -S ./Ampps
else
echo "It's running ..."
fi
(1) I believe ~/.ampps_runner.sh is a bash script, so, its first line should be
#!/bin/bash
or
#!/usr/bin/bash
not
#! /usr/bin/env
(2) Then, the call in zsh script (~/.zshrc) should be:
~/ampps_runner.sh
(3) Note: ~/.ampps_runner.sh should be executable. Change it to executable:
$ chmod +x ~/ampps_runner.sh
The easiest way to run bash temporarily from a zsh terminal is to
exec bash
or just
bash
Then you can run commands you previously could only run in bash. An example
help exec
To exit
exit
Now you are back in your original shell
If you want to know your default shell
echo $SHELL
or
set | grep SHELL=
If you want to reliably know your current shell
ps -p $$
Or if you want just the shell name you might use
ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-'
And you might just put that last one in a function for later, just know that it is only available if it was sourced in a current shell.
whichShell(){
local defaultShell=$(echo $SHELL | tr -d '/bin/')
echo "Default: $defaultShell"
local currentShell=$(ps -p $$ | awk "NR==2" | awk '{ print $4 }' | tr -d '-')
echo "Current: $currentShell"
}
Call the method to see your results
whichShell

Bash syntax issue, 'syntax error: unexpected "do" (expecting "fi")'

I have a sh script that I am using on Windows and Mac/Linux machines, and seems to work with no issues normally.
#!/bin/bash
if [ -z "$jmxname" ]
then
cd ./tests/Performance/JMX/ || exit
echo "-- JMX LIST --"
# set the prompt used by select, replacing "#?"
PS3="Use number to select a file or 'stop' to cancel: "
# allow the user to choose a file
select jmxname in *.jmx
do
# leave the loop if the user says 'stop'
if [[ "$REPLY" == stop ]]; then break; fi
# complain if no file was selected, and loop to ask again
if [[ "$jmxname" == "" ]]
then
echo "'$REPLY' is not a valid number"
continue
fi
# now we can use the selected file, trying to get it to run the shell script
rm -rf ../../Performance/results/* && cd ../jmeter/bin/ && java -jar ApacheJMeter.jar -Jjmeter.save.saveservice.output_format=csv -n -t ../../JMX/"$jmxname" -l ../../results/"$jmxname"-reslut.jtl -e -o ../../results/HTML
# it'll ask for another unless we leave the loop
break
done
else
cd ./tests/Performance/JMX/ && rm -rf ../../Performance/results/* && cd ../jmeter/bin/ && java -jar ApacheJMeter.jar -Jjmeter.save.saveservice.output_format=csv -n -t ../../JMX/"$jmxname" -l ../../results/"$jmxname"-reslut.jtl -e -o ../../results/HTML
fi
I am now trying to do some stuff with a Docker container and have used a node:alpine image, as the rest of my project is NodeJS based, but for some reason the script will not run in the Docker container giving the following -
line 12: syntax error: unexpected "do" (expecting "fi")
How can I fix that? The script seems to be working for every system it's been run on so far, and not thrown up any issues.
The error message indicates that the script is executed as '/bin/sh', and not as /bin/bash. You can see the message with '/bin/sh -n script.sh'
Check how the script is invoked. On different systems /bin/sh is symlinked to bash or other shell that is less feature rich.
In particular, the problem is with the select statement, included in bash, but not part of the POSIX standard.
Another option is that bash on your docker is set to be POSIX compliant by default
#dash-o was correct, and adding -
RUN apk update && apk add bash
to my dockerfile added bash into the container and now it works fine :)

How to execute a command on the remote at login with ssh, after .bashrc sourcing?

I am working on different machines where my home is NFS-mounted. I want to switch easily to another machine if the one I am working on is too much loaded.
I often modify my environment in the shell I am working, and I would like to find the same modified (with respect to the bashrc) environment when I switch to another machine. I tried the following script, but it does not work because the .bashrc is sourced after source $HOME/.env-dump.txt.
Is there a clean way to execute some commands when logging to a machine with ssh as if you type them at the prompt after logged?
#!/usr/bin/env sh
if [[ $# != 1 ]];
echo 'sssh USAGE:'
echo ' sssh remotename'
exit 1
fi
printenv | sed -e '/_=.*/ d;s/\([^=]\+\)=\(.*\)/export \1="\2"/' > $HOME/.env-dump.txt
ssh $1 -t 'source $HOME/.env-dump.txt; bash -l'
Add the following lines to your ~/.bash_profile
[ -f "$HOME/.bashrc" ] && . $HOME/bashrc
[ -f "$HOME/.env-dump.txt" ] && source $HOME/.env-dump.txt
And create a ~/.bash_logout file with the line
[ -f "$HOME/.env-dump.txt" ] && rm $HOME/.env-dump.txt
Now you can simply call ssh $1 -t 'bash -l' in the last line of your script.
WARNING
The output of printenv contains some variables which are machine dependent like GNOME_KEYRING_CONTROL, SESSION_MANAGER, DBUS_SESSION_BUS_ADDRESS ... (These variables are form a Ubuntu 12.04). These variables should be removed from the ~/.env-dump.txt file.

Execute Command From String Dash Linux

So i am trying to learn how to write scripts for Linux OS's so I wrote this download and install script. Although, I know that any good coder for linux would think this is absolute skid work, It works up to par so far so I just have one error at the moment.
CODE:
#!/bin/sh
###################################
#Lystics Core Linux Code v1 #
# #
# Starting Date 4/14 #
# #
# Ending Date ~ #
# #
###################################
clear
#Define Veriables
dir='./LysticsCode/'
url='http://lysticscode.host-elite.com/Linux/Bash%20Scripts/LCode.sh'
file=$(basename "$url")
echo LysticsCode for Linux v1 Installer
echo
read -r -p "Are you sure you wish to install? [Y/n] " a
if [ "$a" = 'n' -o "$a" = 'N' ]; then
#Not going to install
echo 'Exiting The Installation. Thank You! =D'
exit 1;
else
#Set up screen
clear
echo LysticsCode for Linux v1
echo First Installation
echo ''
#Installing
echo Downloading Packages...
curl -o "$dir$file" "$url"
echo ''
echo ''
echo 'Download Complete!'
eval "alias lcode=/root/LysticsCode/Main.sh"
exit 1;
fi
#End Script
$SHELL
What I am trying to do is add a command alias that will allow the installed files to be accessed much easier. I tried using eval "alias lcode=DIR" and it did not work. Same with $(alias lcode=dir)
Can anyone Help?
alias doesn't inherit to child process. You should not invoke a child shell at the end of the script, instead, say save your script to a file named myenv.sh, execute you script in current shell as:
. myenv.sh
$source /root/LysticsCode/Main.sh
Will work.

Bash: how to run a script remotely

I have a script (say run.py) and I want to scp that to a remote machine (say 10.1.100.100), cd into a directory in that remote machine, and execute run.py in that directory.
How do I wrap the above procedure in one single bash script? I don't know how to let bash execute commands remotely in another machine.
Hopefully I can see that stdout of run.py in my terminal. But if I can only redirect it, that's fine as well.
chmod +x ./run.py
scp -pq ./run.py 10.1.100.100:'/home/myremotedirectory/run.py'
ssh 10.1.100.100 'cd /somedirectory && /home/myremotedirectory/run.py'
See if that helps
How to run a local script over SSH
Synopsis:
Script execution over SSH without copying script file.
You need a simple SSH connexion and a local script.
Code:
#!/bin/sh
print_usage() {
echo -e "`basename $0` ssh_connexion local_script"
echo -e "Remote executes local_script on ssh server"
echo -e "For convinient use, use ssh public key for remote connexion"
exit 0
}
[ $# -eq "2" ] && [ $1 != "-h" ] && [ $1 != "--help" ] || print_usage
INTERPRETER=$(head -n 1 $2 | sed -e 's/#!//')
cat $2 | grep -v "#" | ssh -t $1 $INTERPRETER
Examples:
- ssh-remote-exec root#server1 myLocalScript.sh #for Bash
- ssh-remote-exec root#server1 myLocalScript.py #for Python
- ssh-remote-exec root#server1 myLocalScript.pl #for Perl
- ssh-remote-exec root#server1 myLocalScript.rb #for Ruby
Step by step explanations
This script performs this operations:
1° catches first line #! to get interpreter (i.e: Perl, Python, Ruby, Bash interpreter),
2° starts remote interpeter over SSH,
3° send all the script body over SSH.
Local Script:
Local script must start with #!/path/to/interpreter
- #!/bin/sh for Bash script
- #!/usr/bin/perl for Perl script
- #!/usr/bin/python for Python script
- #!/usr/bin/ruby for Ruby script
This script is not based on local script extension but on #! information.
You can do it like this:
ssh -l yourid 10.1.100.100 << DONE
cd /your/dir/
./run.py
DONE
Above has been edited, I don't remember what it was like originally, if I want to do it in one single connection, I will do it this way.
ssh -l yourid 10.1.100.100 python < <(
echo "import os"
echo "os.chdir('/yourdir')"
echo "print(os.getcwd())"
cat yourscript.py
)
Remember, that this is not a rule, that you HAVE TO cd to the requested directory.
Once you get access to the remote machine, just type a relative path to this file, without using cd:
/some_folder/./run.py

Resources