I am trying to create a shell script that once run, adds a line of code to the end of .bashrc then reloads the terminal. This is the code i have written in my install.sh
function addbashaliases() {
echo 'if [ -f ~/aliases/.bash_aliases ]; then
. ~/aliases/.bash_aliases
fi' >> ~/.bashrc;
source ~/.bashrc
}
Nothing is happening. How should I write the code so that it runs and adds the text to the .bashrc file?
For the sake of clarity I prefer to append the information on the .bashrc
file using the cat
command instead of the echo
. However, this should work also using your echo
command.
This said you should make sure that:
- The script calls the
addbashaliases
function
- The
~/aliases/.bash_aliases
file exists (I would expect to have something more similar to ~/.aliases/.bash_aliases
)
You can check that the script has correctly run by checking the content of the ~/.bashrc file and printing some environment variable set on the .bash_aliases
file after the source
command.
#!/bin/bash
function addbashaliases() {
# Add source bash_aliases on .bashrc
cat >> ~/.bashrc << EOT
if [ -f ~/aliases/.bash_aliases ]; then
. ~/aliases/.bash_aliases
fi
EOT
# Reload current environment
source ~/.bashrc
}
# Execute the function
addbashaliases
I am just correcting your script. As per your logic it should be like below.
function addbashaliases() {
if [ -f ~/aliases/.bash_aliases ]; then
output=$(. ~/aliases/.bash_aliases)
echo $output >> ~/.bashrc
fi
source ~/.bashrc
}