Cool Bash Commands and Tricks

By | September 2, 2013

This document has some of my favorite bash commands that helped me in my day to day linux activities. I hope you find them useful.

1: Bind

This command binds a shortcut to already existing command.

For example, if you have a habit of using “clear” the terminal so often, you could use a shortcut “CTRL + L” to do it. What if you want to setup a shortcut to “top” command? This is how you do it.

bind -x ‘”\C-t”:top’

The above command sets “CTRL + t” to top command.

Similarly, bind -x ‘”\C-o”:sudo ifconfig’ sets “CTRL + o” to sudo ifconfig.

2: CTRL – R

Use control + r to search for a command you want to run again. Press ctrl + r and type the command you would want to rerun!

3: Source

This command is used to execute commands from a text file. Source command can run a script (a text file input) even if the file doesn’t have executable permissions.

You can also use it for dynamic loading. If you have list of variables that change often and are available in a text file called /home/variables and you have a script called doit.sh. Using the command “source /home/variables” in doit.sh script would load variables dynamically.

4: Difference between .bash_profile .profile and .bashrc

.bash_profile and .profile are same. If your shell can’t find .bash_profile then it should find .profile .

.bash_profile is read and executed only during login. However, .bashrc is read everytime you type bash on command line.

5: Using alias for shortcut of long commands. Using the following line at .bash_profile or .bashrc would allow you to use get into your working scripts directory with one command, that is cdwork.

alias cdwork=”cd /home/james/office/scripts/work/”

6: hash table

Bash uses hash table to look for commands quickly rather than finding large list of possible places. Use “hash” to see what’s in your hash table.

7: CDPATH

CDPATH, like PATH has list of directories separated with comma. It’s not set by default.

“cd doc” command would look for doc directory in current working directory. If you have the “doc” directory at /home/you/office/work and set

CDPATH=:~/home/you/office/work

then

“cd doc” would look for “doc” directory in /home/you/office/work provided doc is available in the current directory.

8: Comma separated arguments

IFS=,
echo “$*”

9: Character count of variable.

name=james

echo “count = ${#name}”

Now, the output is count = 5

If you like this article, then please consider sharing it. Sharing really inspires us to do things much better!!

Leave a Reply

Your email address will not be published. Required fields are marked *