Create a script that adds lines of code to .bashrc

2019-08-27 20:37发布

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?

标签: linux bash
2条回答
Explosion°爆炸
2楼-- · 2019-08-27 21:11

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
查看更多
姐就是有狂的资本
3楼-- · 2019-08-27 21:13

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
}
查看更多
登录 后发表回答