Bashrc Customization Guide – How to Add Aliases, Use Functions, and More (2024)

Customizing your .bashrc file can greatly improve your workflow and increase your productivity.

The .bashrc is a standard file located in your Linux home directory. In this article I will show you useful .bashrc options, aliases, functions, and more.

The main benefits of configuring the .bashrc file are:

  • Adding aliases allows you to type commands faster, saving you time.
  • Adding functions allows you to save and rerun complex code.
  • It displays useful system information.
  • It customizes the Bash prompt.

How to Get Started with Editing .bashrc

Here's how you can edit the .bashrc file with a text editor:

$ vim ~/.bashrc

You can add date and time formatting to bash history.

HISTTIMEFORMAT="%F %T "
# Output$ history 1017 20210228 10:51:28 uptime 1019 20210228 10:52:42 free -m 1020 20210228 10:52:49 tree --dirsfirst -F 1018 20210228 10:51:38 xrandr | awk '/\*/{print $1}'

Add this line to ignore duplicate commands in the history.

HISTCONTROL=ignoredups

To set the number of lines in active history and to set the number of lines saved in Bash history, add these two lines.

HISTSIZE=2000HISTFILESIZE=2000

You can set your history to append instead of overwriting Bash history. shopt stands for "shell options".

shopt -s histappend

To see all the default shell options, run shopt -p.

# Output$ shopt -pshopt -u autocd shopt -u assoc_expand_once shopt -u cdable_vars shopt -u cdspell shopt -u checkhash shopt -u checkjobs shopt -s checkwinsize [...]

Create some variables to add color to the Bash prompt like this:

blk='\[\033[01;30m\]' # Blackred='\[\033[01;31m\]' # Redgrn='\[\033[01;32m\]' # Greenylw='\[\033[01;33m\]' # Yellowblu='\[\033[01;34m\]' # Bluepur='\[\033[01;35m\]' # Purplecyn='\[\033[01;36m\]' # Cyanwht='\[\033[01;37m\]' # Whiteclr='\[\033[00m\]' # Reset

This is for the Vim lovers. This will allow you to use vim commands on the command line. This is always the first line I add to my .bashrc.

set -o vi

How to Create Aliases in .bashrc

You can use aliases for commands you run a lot. Creating aliases will allow you to type faster, saving time and increasing productivity.

The syntax for creating an alias is alias <my_alias>='longer command'. To find out which commands would make good aliases, run this command to see a list of the top 10 commands you run most.

$ history | awk '{cmd[$2]++} END {for(elem in cmd) {print cmd[elem] " " elem}}' | sort -n -r | head -10
# Output171 git108 cd62 vim51 python338 history32 exit30 clear28 tmux28 tree27 ls

Since I use Git a lot, that would be a great command to create an alias for.

# View Git status.alias gs='git status'# Add a file to Git.alias ga='git add'# Add all files to Git.alias gaa='git add --all'# Commit changes to the code.alias gc='git commit'# View the Git log.alias gl='git log --oneline'# Create a new Git branch and move to the new branch at the same time. alias gb='git checkout -b'# View the difference.alias gd='git diff'

Here are some other useful aliases:

# Move to the parent folder.alias ..='cd ..;pwd'# Move up two parent folders.alias ...='cd ../..;pwd'# Move up three parent folders.alias ....='cd ../../..;pwd'
# Press c to clear the terminal screen.alias c='clear'# Press h to view the bash history.alias h='history'# Display the directory structure better.alias tree='tree --dirsfirst -F'# Make a directory and all parent directories with verbosity.alias mkdir='mkdir -p -v'
# View the calender by typing the first three letters of the month.alias jan='cal -m 01'alias feb='cal -m 02'alias mar='cal -m 03'alias apr='cal -m 04'alias may='cal -m 05'alias jun='cal -m 06'alias jul='cal -m 07'alias aug='cal -m 08'alias sep='cal -m 09'alias oct='cal -m 10'alias nov='cal -m 11'alias dec='cal -m 12'
# Output$ mar March 2021 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 

How to Use Functions in .bashrc

Functions are great for more complicated code when an alias won't work.

Here's the basic function syntax:

function funct_name() {# code;}

This is how you can find the largest files in a directory:

function find_largest_files() { du -h -x -s -- * | sort -r -h | head -20;}
# OutputDownloads $ find_largest_files709Msystemrescue-8.00-amd64.iso337Mdebian-10.8.0-amd64-netinst.iso9.1Mweather-icons-master.zip6.3MHack-font.zip3.9Mcity.list.json.gz2.8Mdvdrental.tar708KIMG_2600.JPG100Ksql_cheat_sheet_pgsql.pdf4.0Krepeating-a-string.txt4.0Kheart.svg4.0KFedora-Workstation-33-1.2-x86_64-CHECKSUM[...]

You can also add colors to the Bash prompt and display the current Git branch like this:

# Display the current Git branch in the Bash prompt.function git_branch() { if [ -d .git ] ; then printf "%s" "($(git branch 2> /dev/null | awk '/\*/{print $2}'))"; fi}# Set the prompt.function bash_prompt(){ PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}}bash_prompt
Bashrc Customization Guide – How to Add Aliases, Use Functions, and More (1)

Grep (search) through your history for previous run commands:

function hg() { history | grep "$1";}
# Output$ hg vim305 2021-03-02 16:47:33 vim .bashrc307 2021-03-02 17:17:09 vim .tmux.conf

This is how you start a new project with Git:

function git_init() { if [ -z "$1" ]; then printf "%s\n" "Please provide a directory name."; else mkdir "$1"; builtin cd "$1"; pwd; git init; touch readme.md .gitignore LICENSE; echo "# $(basename $PWD)" >> readme.md fi}
# Output$ git_init my_project/home/brandon/my_projectInitialized empty Git repository in /home/brandon/my_project/.git/

You can also get the weather report on the command line. This requires the package curl, jq, and an API key from Openweathermap. Read the Openweathermap API documentation in order to configure the URL correctly to get the weather in your location.

Install curl and jq with these commands:

$ sudo apt install curl jq# OR$ sudo dnf install curl jq
function weather_report() { local response=$(curl --silent 'https://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial&appid=<YOUR_API_KEY>') local status=$(echo $response | jq -r '.cod')# Check for the 200 response indicating a successful API query. case $status in 200) printf "Location: %s %s\n" "$(echo $response | jq '.name') $(echo $response | jq '.sys.country')" printf "Forecast: %s\n" "$(echo $response | jq '.weather[].description')" printf "Temperature: %.1f°F\n" "$(echo $response | jq '.main.temp')" printf "Temp Min: %.1f°F\n" "$(echo $response | jq '.main.temp_min')" printf "Temp Max: %.1f°F\n" "$(echo $response | jq '.main.temp_max')" ;; 401) echo "401 error" ;; *) echo "error" ;; esac}
# Output$ weather_reportLocation: "New York" "US"Forecast: "clear sky"Temperature: 58.0°FTemp Min: 56.0°FTemp Max: 60.8°F

How to Print System Information in .bashrc

You can display useful system information when you open the terminal like this:

clearprintf "\n"printf " %s\n" "IP ADDR: $(curl ifconfig.me)"printf " %s\n" "USER: $(echo $USER)"printf " %s\n" "DATE: $(date)"printf " %s\n" "UPTIME: $(uptime -p)"printf " %s\n" "HOSTNAME: $(hostname -f)"printf " %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)"printf " %s\n" "KERNEL: $(uname -rms)"printf " %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)"printf " %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1" "}')"printf " %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3"/"$2}')"printf "\n"

Output:

Bashrc Customization Guide – How to Add Aliases, Use Functions, and More (2)

Source the .bashrc file to make the changes take effect:

$ source ~/.bashrc

Here are all these custom .bashrc settings together. On a new system I paste any customization below the default code in the .bashrc file.

######################################################################### ██████╗ █████╗ ███████╗██╗ ██╗██████╗ ██████╗# ██╔══██╗██╔══██╗██╔════╝██║ ██║██╔══██╗██╔════╝# ██████╔╝███████║███████╗███████║██████╔╝██║ # ██╔══██╗██╔══██║╚════██║██╔══██║██╔══██╗██║ # ██████╔╝██║ ██║███████║██║ ██║██║ ██║╚██████╗# ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝########################################################################set -o viHISTTIMEFORMAT="%F %T "HISTCONTROL=ignoredupsHISTSIZE=2000HISTFILESIZE=2000shopt -s histappendblk='\[\033[01;30m\]' # Blackred='\[\033[01;31m\]' # Redgrn='\[\033[01;32m\]' # Greenylw='\[\033[01;33m\]' # Yellowblu='\[\033[01;34m\]' # Bluepur='\[\033[01;35m\]' # Purplecyn='\[\033[01;36m\]' # Cyanwht='\[\033[01;37m\]' # Whiteclr='\[\033[00m\]' # Resetalias gs='git status'alias ga='git add'alias gaa='git add --all'alias gc='git commit'alias gl='git log --oneline'alias gb='git checkout -b'alias gd='git diff'alias ..='cd ..;pwd'alias ...='cd ../..;pwd'alias ....='cd ../../..;pwd'alias c='clear'alias h='history'alias tree='tree --dirsfirst -F'alias mkdir='mkdir -p -v'alias jan='cal -m 01'alias feb='cal -m 02'alias mar='cal -m 03'alias apr='cal -m 04'alias may='cal -m 05'alias jun='cal -m 06'alias jul='cal -m 07'alias aug='cal -m 08'alias sep='cal -m 09'alias oct='cal -m 10'alias nov='cal -m 11'alias dec='cal -m 12'function hg() { history | grep "$1";}function find_largest_files() { du -h -x -s -- * | sort -r -h | head -20;}function git_branch() { if [ -d .git ] ; then printf "%s" "($(git branch 2> /dev/null | awk '/\*/{print $2}'))"; fi}# Set the prompt.function bash_prompt(){ PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}}bash_promptfunction git_init() { if [ -z "$1" ]; then printf "%s\n" "Please provide a directory name."; else mkdir "$1"; builtin cd "$1"; pwd; git init; touch readme.md .gitignore LICENSE; echo "# $(basename $PWD)" >> readme.md fi}function weather_report() { local response=$(curl --silent 'https://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial&appid=<YOUR_API_KEY>') local status=$(echo $response | jq -r '.cod') case $status in 200) printf "Location: %s %s\n" "$(echo $response | jq '.name') $(echo $response | jq '.sys.country')" printf "Forecast: %s\n" "$(echo $response | jq '.weather[].description')" printf "Temperature: %.1f°F\n" "$(echo $response | jq '.main.temp')" printf "Temp Min: %.1f°F\n" "$(echo $response | jq '.main.temp_min')" printf "Temp Max: %.1f°F\n" "$(echo $response | jq '.main.temp_max')" ;; 401) echo "401 error" ;; *) echo "error" ;; esac}clearprintf "\n"printf " %s\n" "IP ADDR: $(curl ifconfig.me)"printf " %s\n" "USER: $(echo $USER)"printf " %s\n" "DATE: $(date)"printf " %s\n" "UPTIME: $(uptime -p)"printf " %s\n" "HOSTNAME: $(hostname -f)"printf " %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)"printf " %s\n" "KERNEL: $(uname -rms)"printf " %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)"printf " %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1" "}')"printf " %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3"/"$2}')"printf "\n"

Conclusion

In this article you learned how to configure various .bashrc options, aliases, functions, and more to greatly improve your workflow and increase your productivity.

Follow me on Github | Dev.to.

Bashrc Customization Guide – How to Add Aliases, Use Functions, and More (2024)
Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 6215

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.