Tired of typing the same long commands over and over again? Do you feel inefficient working on the command line? Bash aliases can create a world of difference for you.

Bash aliasing is a way to supplement or override Bash commands with new commands. Bash aliases make it easy for users to customize their experience in POSIX terminals. They are usually defined in $HOME/.bashrc or $HOME/bash_aliases (which is loaded by $HOME/.bashrc).

Most distributions add at least some popular aliases to the default.bashrc file for new user accounts. These can be used to briefly demonstrate the syntax of Bash aliases:

alias ls='ls -F'
alias ll='ls -lh'
Copy the code

But not all distributions come with pre-added aliases. If you want to add aliases manually, you must load them into your current Bash session:

$ source ~/.bashrc
Copy the code

Otherwise, you can close the terminal and reopen it in order to reload its configuration file.

With the aliases defined in the Bash initialization script, you can type LL and get ls -l, and when you type LS, you get normal output that is not the original LS.

Those aliases are great, but they’re only scratches in the surface. Here are ten Bash aliases that you’ll never be able to live without once you try them.

The first set

To start, create a file named ~/.bash_aliases:

$ touch ~/.bash_aliases
Copy the code

Then, make sure the code appears in your ~/.bashrc file:

if [ -e $HOME/.bash_aliases ]; then
    source $HOME/.bash_aliases
fi
Copy the code

If you want to try any of the aliases in this article for yourself, type them into the.bash_aliases file and load them into your current Bash session using the source ~/.bashrc command.

Sort by file size

If you’ve started with GUI file managers like Nautilus in GNOME, Finder in MacOS, or Explorer in Windows, you’re probably used to sorting file lists by file size. You can also do this on a terminal, but this command is not very neat.

Add this alias to the configuration on the GNU system:

alias lt='ls --human-readable --size -1 -S --classify'
Copy the code

This alias replaces lt with the ls command, which displays the size of each item in a single column and then sorts it by size, using symbols to indicate the file type. Load a new alias and try it:

$ source~/.bashrc $ lt total 344K 140K configure* 44K aclocal.m4 36K LICENSE 32K config.status* 24K Makefile 24K Makefile.in 12K Config.log 8.0k readme.md 4.0k info.slackermedia.git-portal. json 4.0k git-portal.spec 4.0k flatpak.path.patch 4.0K Makefile.am* 4.0k dot-gitlab.ci.yml 4.0k configure.ac* 0 autom4te.cache/ 0 share/ 0 bin/ 0 install-sh @0 compile @0 missing@ 0 COPYING@Copy the code

On MacOS or BSD, the ls command does not have the same options, so this alias can be changed to:

alias lt='du -sh * | sort -h'
Copy the code

This version has slightly different results:

$du - sh * | sort - h COPYING the compile 0 0 0 install - sh 0 missing 4.0 K configure. Ac 4.0 K dot - gitlab. Ci. Yml 4.0 K Flatpak.path. patch 4.0k git-portal.spec 4.0k info.slackermedia.git-portal. json 4.0k makefile.am 8.0k readme.md 12K config.log 16K bin 24K Makefile 24K Makefile.in 32K config.status 36K LICENSE 44K aclocal.m4 60K share 140K configure 476K autom4te.cacheCopy the code

In fact, even on Linux, the above command is useful because directories and symbolic links listed using ls have a size of 0, which may not be the information you really want. Which one to use is up to you.

Thanks to Brad Alexander for the idea of this alias.

View only mounted drives

The mount command used to be simple. With one command, you can get a list of all the mounted file systems on your computer, which is often used for an overview of what drives are connected to your workstation. In the past it would have been impressive to see more than three or four entries, since most computers don’t have that many USB ports, so the results were relatively easy to see.

Now that computers are a bit more complex, with LVMS, physical drives, network storage, and virtual file systems, it’s hard to see the results of mount:

sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=8131024k,nr_inodes=2032756,mode=755)
securityfs on /sys/kernel/security typesecurityfs (rw,nosuid,nodev,noexec,relatime) [...]  /dev/nvme0n1p2 on /boottype ext4 (rw,relatime,seclabel)
/dev/nvme0n1p1 on /boot/efi typevfat (rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=ascii,shortname=winnt,errors=remount-ro) [...]  gvfsd-fuse on /run/user/100977/gvfstype fuse.gvfsd-fuse (rw,nosuid,nodev,relatime,user_id=100977,group_id=100977)
/dev/sda1 on /run/media/seth/pocket type ext4 (rw,nosuid,nodev,relatime,seclabel,uhelper=udisks2)
/dev/sdc1 on /run/media/seth/trip type ext4 (rw,nosuid,nodev,relatime,seclabel,uhelper=udisks2)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,relatime)
Copy the code

To solve this problem, try this alias:

alias mnt='mount | awk -F' ' '{ printf "%s\t%s\n".The $1.$3; }' | column -t | egrep ^/dev/ | sort'
Copy the code

This alias uses AWk to parse mount’s output by column, reducing the output to what you might want to look for (which hard drives are mounted, not file systems) :

$ mnt /dev/mapper/fedora-root / /dev/nvme0n1p1 /boot/efi /dev/nvme0n1p2 /boot /dev/sda1 /run/media/seth/pocket /dev/sdc1  /run/media/seth/tripCopy the code

On MacOS, the mount command does not provide very detailed output, so this alias may be overly concise. However, if you prefer concise reports, try the following:

alias mnt='mount | grep -E ^/dev | column -t'
Copy the code

Results:

$ mnt
/dev/disk1s1  on  /                (apfs,  local,  journaled)
/dev/disk1s4  on  /private/var/vm  (apfs,  local,  noexec,     journaled,  noatime,  nobrowse)
Copy the code

Look for commands in your grep history

Sometimes you figure out how to do something on the terminal and feel like you’ll never forget what you just learned. And then, an hour later you completely forget what you did.

Searching Bash history is something everyone does from time to time. If you know exactly what to search for, you can use Ctrl + R to do a reverse search of history, but sometimes you can’t remember the exact command to look for.

Here’s an alias to make the task easier:

alias gh='history|grep'
Copy the code

Here’s an example of how to use it:

$ gh bash
482 cat ~/.bashrc | grep _alias
498 emacs ~/.bashrc
530 emacs ~/.bash_aliases
531 source ~/.bashrc
Copy the code

Sort by modification time

It happens every Monday: you sit down at your computer and start working, you open a terminal, and you realize you’ve forgotten what you were doing last Friday. What you need is to list the aliases of the recently modified files.

You can create aliases using the ls command to help you find the last location you left:

alias left='ls -t -1'
Copy the code

The output is simple, but you can extend it with the –long option if you wish. This alias is listed as follows:

$ left
demo.jpeg
demo.xcf
design-proposal.md
rejects.txt
brainstorm.txt
query-letter.xml
Copy the code

File count

If you need to know how many files are in a directory, this solution is one of the most typical examples of UNIX command construction: use the ls command to list the file, control its output to a single column with the -1 option, and then pipe it to the WC (word count) command to count how many lines there are.

This is a great demonstration of how the UNIX philosophy allows users to build their own solutions using small system components. If you happen to do this a few times a day, this command combination also requires typing a lot of letters, and without using the -r option, it won’t work for directories, which introduces new lines into the output and results in useless results.

This alias makes the process easier:

alias count='find . -type f | wc -l'
Copy the code

This alias evaluates files, ignoring directories, but not the contents of directories. If you have a project folder with two directories, each containing two files, this alias will return 4 because there are four files in the entire project.

$ ls
foo   bar
$ count
4
Copy the code

Create the Python virtual environment

Do you program in Python?

Do you write a lot of programs in Python?

If so, then you know that creating a Python virtual environment requires at least 53 keystrokes.

This number is 49 times redundant, and is easily solved by two new aliases called VE and VA:

alias ve='python3 -m venv ./venv'
alias va='source ./venv/bin/activate'
Copy the code

Running ve creates a new directory called venv that contains Python 3’s common virtual environment file systems. The VA alias activates the environment in the current shell:

$ cd my-project
$ ve
$ va
(venv) $
Copy the code

Add a replication progress bar

Everyone makes fun of progress bars because they always seem out of place. Deep down, though, we all seem to want them. The UNIX cp command does not have a progress bar, but it does have a -v option for displaying details, which echoes each filename copied to the terminal. This is a pretty good trick, but it’s not so useful when you’re copying a large file and want to know how many files haven’t been transferred yet.

The pv command can provide a progress bar during replication, but it is not commonly used. The rsync command, on the other hand, is included with the default installation of almost all POSIX systems, and is generally considered one of the smartest ways to copy files remotely and locally.

Even better, it has a built-in progress bar.

alias cpv='rsync -ah --info=progress2'
Copy the code

Use this alias as if using the cp command:

$CPV bigfile.flac /run/media/ Seth /audio/ 3.83m 6% 213.15MB/s 0:00:00 (XFR#4, to-chk=0/4)
Copy the code

An interesting side effect of using this command is that rsync does not require the -r flag to copy files and directories, whereas cp does.

Avoid accidental deletion

You should not use the rm command. The RM manual even says:

** Warning: ** If you delete a file using RM, you can usually recover the contents of the file. If you want to be even more sure that your content is truly unrecoverable, consider using Shred.

If you want to delete files, you should move them to the wastebasket, just as you would with a desktop.

POSIX makes this easy because the trash can is a physical location accessible in the file system. This location may change depending on your platform: On FreeDesktop, ‘Trash’ is located at ~/.local/share/Trash, and on MacOS it’s ~/.Trash, but anyway, it’s just a directory where you can hide files out of sight until you’re ready to delete them permanently.

This simple alias provides a way to throw files from the terminal into the trash:

alias tcn='mv --force -t ~/.local/share/Trash '
Copy the code

This alias uses a little-known MV flag (-t), which allows you to supply parameters as the final move target, ignoring the usual requirement to list the files to move first. Now you can use the new command to move files and folders to the system trash:

$ ls
foo  bar
$ tcn foo
$ ls
bar
Copy the code

Now that the file is “gone,” you only realize you need it when you’re in a cold sweat. At this point, you can salvage the file from the system trash; This should certainly give Bash and MV developers some help.

** Note: ** If you need a more powerful trash can command with better FreeDesktop compatibility, see Trashy.

Simplifying Git workflow

Everyone has their own unique workflow, but no matter what, there are usually repetitive tasks. If you use Git a lot, you may find yourself repeating sequences of actions a lot. You might find yourself going back to the main branch and pulling the latest changes over and over all day, or you might find yourself creating tags and pushing them to the far end, or it might be something else entirely.

Whatever Git spells you’re tired of typing over and over again, you can ease some of the pain with Bash aliases. Thanks in large part to its ability to pass arguments to hooks, Git has a rich set of introspection commands that saves you from having to execute ugly, verbose commands in Bash.

For example, while you might have a hard time finding a project’s top-level directory in Bash (which in Bash’s case is a completely arbitrary name, since the absolute top-level of a computer is the root directory), Git can find a project’s top-level directory with a simple query. If you study Git hooks, you’ll find that you can find all sorts of information Bash doesn’t know about, and you can use Bash aliases to take advantage of that information.

This is an alias to find the top level directory of your Git project. Regardless of which project you are currently working on, you can change the directory to the top level directory, switch to the main branch, and perform a Git pull:

alias startgit='cd `git rev-parse --show-toplevel` && git checkout master && git pull'
Copy the code

This alias is by no means a universally useful one, but it demonstrates how a relatively simple alias can eliminate a lot of tedious navigation, commands, and waiting prompts.

A simpler, and possibly more generic, alias will return you to the top-level directory of your Git project. This alias is useful because when you work on a project, that project more or less becomes your “temporary home directory.” It should be as simple as going home, like going to your real home, here’s an alias:

alias cg='cd `git rev-parse --show-toplevel`'
Copy the code

Now, the CG command takes you to the top of your Git project, no matter how deep you dive into the directory structure.

Switch directories and view the contents at the same time

A famous scientist once suggested that we could solve many of earth’s energy problems by harvesting the energy consumed by geeks typing CD followed by LS.

This is a common use because often when you change a directory, you feel the urge or need to see what’s around you.

But moving through your computer’s directory tree doesn’t have to be a stop-and-go process.

This is a cheat because it’s not an alias at all, but it’s a good excuse to explore Bash’s capabilities. While aliases are great for quickly replacing a command, Bash also allows you to add native functions to.bashrc files (or separate function files that you load into.bashrc, just like your alias files).

To stay modular, create a new file called ~/.bash_functions and have your.bashrc load it:

if [ -e $HOME/.bash_functions ]; then
    source $HOME/.bash_functions
fi
Copy the code

In the function file, add this code:

function cl() {
    DIR="$*";
        # if no DIR given, go home
        if [ $# -lt1];then
                DIR=$HOME;
    fi;
    builtin cd "${DIR}"& & \# use your preferred ls command
        ls -F --color=auto
}
Copy the code

Load the function into a Bash session and try:

$ source ~/.bash_functions
$ cl Documents
foo bar baz
$ pwd
/home/seth/Documents
$ cl ..
Desktop  Documents  Downloads
[...]
$ pwd
/home/seth
Copy the code

Functions are more flexible than aliases, but with that flexibility, you are responsible for making sure your code makes sense and lives up to your expectations. Aliases are simple, so keep them simple and useful. To formally modify Bash’s behavior, use a function saved somewhere in the PATH environment variable or a custom shell script.

As a side note, there are some clever tricks to implement CD and LS sequences as aliases, so if you are patient enough, even a simple alias will never end.

Start aliasing and functionalizing

Being able to customize your environment makes Linux so fun and efficient and makes Linux life-changing. Start using simple aliases, move on to functions, and post the aliases you must have in the comments!


Via: opensource.com/article/19/…

By Seth Kenlon (lujun9972

This article is originally compiled by LCTT and released in Linux China