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

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

Related

script file not found when using source

I have a bash script in a file named reach.sh.
This file is given exe rights using chmod 755 /Users/vb/Documents/util/bash/reach.sh.
I then created an alias using alias reach='/Users/vb/Documents/util/bash/reach.sh'
So far this works great.
It happens that I need to run this script in my current process, so theoretically I would need to add . or source before my script path.
So I now have alias reach='source /Users/vb/Documents/util/bash/reach.sh'
At this point when I run my alias reach, the script is failing.
Error /Users/vb/Documents/util/bash/reach.sh:7: = not found
Line 7 if [ "$1" == "cr" ] || [ "$1" == "c" ]; then
Full script
#!/bin/bash
# env
REACH_ROOT="/Users/vb/Documents/bitbucket/fork/self"
# process
if [ "$1" == "cr" ] || [ "$1" == "c" ]; then
echo -e "Redirection to subfolder"
cd ${REACH_ROOT}/src/cr
pwd
else
echo -e "Redirection to root folder"
cd ${REACH_ROOT}
pwd
fi
Any idea what I could be missing ?
I'm running my script in zsh which is not a bash shell, so when I force it to run in my current process it runs in a zsh shell and does not recognize bash commands anymore.
In your question, you say "It happens that I need to run this script in my current process", so I'm wondering why you are using source at all. Just run the script. Observe:
bash-script.sh
#!/bin/bash
if [ "$1" == "aaa" ]; then
echo "AAA"
fi
zsh-script.sh
#!/bin/zsh
echo "try a ..."
./bash-script.sh a
echo "try aaa ..."
./bash-script.sh aaa
echo "try b ..."
./bash-script.sh b
output from ./zsh-script.sh
try a ...
try aaa ...
AAA
try b ...
If, in zsh-script.sh, I put source in front of each ./bash-script.sh, I do get the behavior you described in your question.
But, if you just need to "run this script in my current process", well, then ... just run it.
source tries to read a file as lines to be interpreted by the current shell, which is zsh as you have said. But simply running it, causes the first line (the #!/bin/bash "shebang" line) to start a new shell that interprets the lines itself. That will totally resolve the use of bash syntax from within a zsh context.

bad interpreter no such file or directory

Thank you for reviewing my shell script i am producing this error but not sure why it is not running. I am a noob when it comes to shell scripting. Please help. Here is my code:
#!/bin/bash
#This script creates the log files based on the current date and hour
#Variables for managing the logs
LOG_DIRECTORY=/var/log; export LOG_DIRECTORY
LOG_DIRECTORY_FILE=/var/log/secure; export LOG_DIRECTORY_FILE
MY_LOG_DIRECTORY=$LOG_DIRECTORY/mylogs; export MY_LOG_DIRECTORY
MY_LOG_FILE=$MY_LOG_DIRECTORY/mylog-`date +%m-%d-%H`; export MY_LOG_FILE
EXPRESSTION=`date '+%b %d %H'`; export MY_LOG_FILE
#Checks if mylog directory exists.If not, then creates it
if [ ! -d "$MY_LOG_DIRECTORY" ]; then
mkdir -p $MY_LOG_DIRECTORY
fi
#Scripts exits successfully, If the log already exists
if [ -f "$MY_LOG_FILE" ]; then
echo "Log file already exists. Nothing is written to log";
exit 0;
fi
#grep the contents to the log file
grep "^$EXPRESSTION" $LOG_DIRECTORY_FILE >> $MY_LOG_FILE
echo "New myLog file created successfully"
Your script needs to be saved as a UNIX text file.
Try running dos2unix on it, or open it up in vim and run :set fileformat=unix and save.
If you don't have dos2unix, and aren't comfortable with vim, you can use perl:
perl -pi -e 's/\r\n?/\n/g' your-script-filename
"bad interpreter no such file or directory" error indicates /bin/bash does not exist.
Try to run script as
$ sh log.sh
OR use some other available shell interpreter (e.g /bin/sh , /bin/ksh) instead of /bin/bash

Shell script to set environment variables

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 =.

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 !

exiting script while running source scriptname over SSH

I have a script with a number of options in it one of the option sets is supposed to change the directory and then exit the script however running over ssh with the source to get it to change in the parent it exits SSH is there another way to do this so that it does not exit? my script is in the /usr/sbin directory.
You might try having the script run a subshell instead of whatever method it is using to “change [the directory] in the parent” (presumably you have the child print out a cd command and have the parent do something like eval "$(script --print-cd)"). So instead of (e.g.) a --print-cd option, add a --subshell option that starts a new instance of $SHELL.
d=/path/to/some/dir
#...
cd "$d"
#...
if test -n "$opt_print_cd"; then
sq_d="$(printf %s "$d" | sed -e "s/'/'\\\\''/g")"
printf "cd '%s'\n" "$sq_d"
elif test -n "$opt_subshell"; then
exec "$SHELL"
fi
If you can not edit the script itself, you can make a wrapper (assuming you have permission to create new, persistent files on the ‘server’):
#!/bin/sh
script='/path/to/script'
print_cd=
for a; do test "$a" = --print-cd && print_cd=yes && break; done
if test -n "$print_cd"; then
eval "$("$script" ${1+"$#"})" # use cd instead of eval if the script prints a bare dir path
exec "$SHELL"
else
exec $script" ${1+"$#"}
fi

Resources