Shell script to set environment variables - shell

I wish to write a shell script to export variables.
Below I have listed the script .
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH='/home/linux/Practise/linux-devkit/bin/:$PATH';
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-';
echo "Export CROSS_COMPILE done"
But this doesn't seem to work properly. I have to individually execute the commands at the shell prompt instead.

You need to run the script as source or the shorthand .
source ./myscript.sh
or
. ./myscript.sh
This will run within the existing shell, ensuring any variables created or modified by the script will be available after the script completes.
Running the script just using the filename will execute the script in a separate subshell.

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.
Meanwhile you have to use double quotes not single quote to expand variables:
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
Semicolons at the end of a single command are also unnecessary.
So far:
#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
For su you can run it with:
su -c 'sh /path/to/script.sh'
Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

Run the script as source= to run in debug mode as well.
source= ./myscript.sh

I cannot solve it with source ./myscript.sh. It says the source not found error.
Failed also when using . ./myscript.sh. It gives can't open myscript.sh.
So my option is put it in a text file to be called in the next script.
#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
Tnen call it whenever is needed:
while read -r line; do
line=$(sed -e 's/[[:space:]]*$//' <<<${line})
var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt

In my case, I gave extra spaces before and after =.
For example, in my shell file(say deploy.sh)
I initially write
GIT_SHA = $(git rev-parse HEAD)
But I fixed it by using:
GIT_SHA=$(git rev-parse HEAD)
So please note that we should not give any spaces before and after the =.

Related

Set environment variable on branch checkout/switch

I'm using the post-checkout hook to try and set environment variables when switching branches.
#!/bin/sh
echo "Updating environment variables..."
OLD_IFS=$IFS
IFS=$'\n'
for x in $(cat .env | sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
do
var_name=$( cut -d '=' -f 1 <<< "$x" )
export $x
pwsh.exe -c "\$env:$x"
pwsh.exe -c "echo 1; echo \$env:$var_name"
export $x
done
IFS=$OLD_IFS
The problem is that git hook is executed with WSL so the variables I set are lost after the post-hook
I assume this is because of the shebang?
I've tried #!/usr/bin/env pwsh but I get the error Processing -File '.git/hooks/post-checkout' failed because the file does not have a '.ps1' extension. Specify a valid PowerShell script file name, and then try again.
Is this something that can be done? I want to automatically change the DB connection when I switch branches.
As anthony sottlie noted, you can't do it that way.
What you need instead is a command that you run instead of git switch or git checkout. In this command, you will:
run git switch or git checkout, then
set the environment variables you would have set in your script, the way you would have set them
and since this will be done by the command itself, rather than in a subprocess, it will affect further commands run by this same command-line interpreter.

Alias command incorrectly executing

I am attempting to load my git aliases from a gist on github. For some reason, the command executes find, but when I attempt to execute any of the aliases, they are either incorrectly mapped — e.g., gsts -> git stash instead of gsts -> git status — or they are not mapped at all.
#!/bin/bash
update_git_aliases(){
GIST_URL='https://gist.githubusercontent.com/Moyoka22/ec605b0b52fee6d6d30d5f72822938f4/raw/git-aliases'
RESPONSE="$(wget --no-cache -qO- ${GIST_URL})"
if [ ${?} -ne 0 ]
then
echo 'Download failed. Exiting.'
return 1
fi
echo ${RESPONSE} > ${1}
chmod +x ${1}
}
DOWNLOAD_FAILED=0
ALIAS_FILE="${HOME}/.config/git-aliases"
if [ ! -f ${ALIAS_FILE} ]
then
echo "Git aliases not found! Downloading..."
update_git_aliases ${ALIAS_FILE}
DOWNLOAD_FAILED=${?}
fi
if [ ${DOWNLOAD_FAILED} -ne 0 ]
then
echo "Downloading aliases failed."
exit 1
fi
cat ${ALIAS_FILE} | bash
I assume you want the aliases on your interactive shell, so remove the last cat as it's useless and once ${HOME}/.config/git-aliases is created
$ source "${HOME}/.config/git-aliases"
The alias commands must be run in your current shell process to have an effect.
cat ${ALIAS_FILE} | bash executes the alias commands in ALIAS_FILE in a new child process, not your shell, and not the program's shell.
source runs the commands in the current shell. You need to source the file from your current shell, not from the program. You can do this after the file is updated. In order to make this permanent, you will need to add source "${HOME}/.config/git-aliases" to your shell config.
What many programs like this do is print out the necessary commands at the end.
echo "$ALIAS_FILE updated"
echo "Make sure `source $ALIAS_FILE` is in your $HOME/.bash_profile"
echo "Run `source $ALIAS_FILE` to use it in your current shell"

How do I write a script that shows all aliases upon startup of terminal

I am a new user learning to use Linux. I am currently running Ubuntu 18.04 with several aliases created, and saved in the ~/.bashrc directory. I am trying to write a welcome script that also displays the current aliases upon start up. The current code I have is as follows:
#! /bin/bash
echo -e "\nWelcome $USER"
echo -e "Today's date is: \c"
date
echo -e "\vHave \vA \VGreat \vDay! \c"
echo -e "\nCurrent aliases for reference are:"
alias
Upon startup, or running the script on it's own, the welcome message runs but the actual alias command does not?
First things first:
(...) saved in the ~/.bashrc directory. (...)
Well, I must point that .bashrc is a file, not a directory, and is part of the Bash startup files.
That said, the reason why running the alias command inside a script does not work as expected is that it is a shell builtin, and when invoking it from a script will not behave as if running it from your shell.
Hence, the quickest thing you can do is store your aliases in a different file, like ~/.bash_aliases and ensure it will be loaded by adding this to your .bashrc file:
if [ -f ~/.bash_aliases ]; then
source ~/.bash_aliases
fi
And then read that file directly from your script:
#! /bin/bash
echo -e "\nWelcome $USER"
echo -e "Today's date is: \c"
date
echo -e "\vHave \vA \VGreat \vDay! \c"
echo -e "\nCurrent aliases for reference are:"
cat ~/.bash_aliases

xenv shell changing into sub-shell

I am writing a ksh to checkout the code and setup the compilation variables through xenv setup. This is how my script looks at the moment -
#!/usr/bin/ksh
logname=$LOGNAME
homedir="$HOME/${logname}-SVN-Dev/pkgroot"
#Create directory <username>-SVN-Dev to contain copied code.
if [ -z "$logname" ]
then
logname=`/usr/ucb/whoami`
fi
RunCmd "rm -rf $homedir"
RunCmd "mkdir -p $homedir"
## Some code to checkout code
cd $HOME
echo "setenv PKGROOT $homedir">>$HOME/.cshrc
echo "setenv DEVROOT $homedir/src">>$HOME/.cshrc
source $HOME/.cshrc
RunCmd "/xenv/xenv -L -i $homedir/My.env $homedir;"
make -f project.mk createmakefile
The xenv above switches the shell and goes into a new prompt, ia_cross: and my shell exits without executing the "make -f project.mk createmakefile" command.
I have tries putting a pipe between make and xenv but that didn't solve this. Any suggestions would really help?
use below command in your script,
echo "make -f project.mk createmakefile" | /xenv/xenv -c -i $homedir/My.env $homedir;

Linux source does not work in .sh file?

I have a .sh (start_sim.sh) and a .bash (sim_sources.bash) file.
The sim_sources.bash file is called from within the start_sim.sh and should set an environment variable $ROBOT to a certain value. However the ROBOT variable never changes when I call ./start_sim.sh. Is there a fundamental mistake in the way I am trying to do this?
start_sim.sh contains:
#!/bin/bash
echo -n "sourcing sim_sources.bash..."
source /home/.../sim_sources.bash
echo "done."
sim_sources.bash contains:
# set the robot id
export ROBOT=robot
EDIT: Could you also propose a way to work around this issue? I would still need to set variables from with in the .bash file.
EDIT2:
Thanks for your replys!
Finally I ended up solving it with a screen and stuffing commands to it:
echo -n "starting screen..."
screen -dmS "sim_screen"
sleep 2
screen -S "sim_screen" -p 0 -X stuff "source /home/.../sim_sources.bash$(printf \\r)"
sleep 5
screen -S "sim_screen" -p 0 -X stuff "source /home/.../start_sim.sh$(printf \\r)"
You're setting the ROBOT variable in the start_sim.sh script, but that's not available to parent processes (your spawning shell/command-prompt).
Exporting a variable e.g. export ROBOT=robot makes the variable available to the current process and child processes. When you invoke ./start_sim.sh you're invoking a new process.
If you simply source start_sim.sh in your shell, that script runs as part of your shell process and then your variable will be available.
As Brian pointed out the variables are not available outside of the script.
Here a adapted script that shows this point:
#!/bin/bash
echo -n "sourcing sim_sources.bash..."
. sim_sources.bash
echo $ROBOT
echo "done."
The workaround you are asking for is to start a new shell from the actual shell with the environmental values already set:
#!/bin/bash
echo -n "sourcing sim_sources.bash..."
. sim_sources.bash
echo "done."
bash
This results in:
bash-4.1$ printenv | grep ROBOT
ROBOT=robot
I am on Ubuntu 16.04
I used /bin/sh instead of /bin/bash and it works !

Resources