Create a script that adds lines of code to .bashrc

2019-08-27 20:40发布

问题:

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?

回答1:

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


回答2:

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
}


标签: linux bash