Bash Terminal

 

 

Terminal Power

The command line, or terminal, is one of the tools you will use most in your development career. Learning how to use the command line will not only increase your productivity, it will give you insight on how your machine operates. Plus it’s what all the cool kids are doing!

In the sections below, we will go over the basics needed for most common development roles. I have gone over the basic commands briefly but have provided a slightly more in-depth dive into those I believe require additional explanation or examples. This is not meant to be an exhaustive list, but rather a gradual introduction to the most common commands a developer will be using in his or her daily routine.

 


 

The User Basics

These commands are the common user commands that even non-developers should know. They are used so frequently, you are likely to already know them, but I have included them for those new to the command line, and as a refresher for those that do know them.

 

pwd

To print out the directory you are currently in, use the pwd command. This is the directory you are currently in.

$ pwd
/home/user

 

 

cp

To copy a file, use the cp command. The first file will be copied to the second file location. If the second file already exists, the file will be overwritten, so be careful when copying files.

$ cp filename1 filename2

 

 

mv

To move a file, use the mv command. It looks very similar to the cp command. When you want to rename a file, use the mv command.

$ mv filename1 filename2

 

 

rm

To delete a file, use the rm command

$ rm filename

 

To remove all file recursively, including directories, use the -r option. A safer method is to prompt before each removal, using the -i command in conjunction with the -r command.

$ rm -ir projects
rm: descend into directory 'projects'? y
rm: remove regular empty file 'test'? y
rm: remove directory 'projects'? y

 

 

mkdir

To create a directory, use the mkdir command.

$ mkdir newdir

 

 

rmdir

To remove an empty directory, use the rmdir command. If the directory is not empty, use rm -r to remove the directory and everything it contains.

$ rmdir newdir

 

 

cd

To change the directory you’re in, use the cd command followed by the directory.

$ cd /path/of/directory

 

The root of the filesystem is /.

$ cd /
$ pwd
/

 

The tilde, ~, can be used as a shortcut to your home directory so you do not need to type out the full /home/username when changing to a directory in your home directory.

$ cd ~/Documents
$ pwd
/home/user/Documents

 

To move to the top level of your home directory, use just the cd command with no additional options.

$ cd
$ pwd
/home/user

 

./ refers to your current working directory. The command below will change your directory to the projects folder inside the current directory.

$ cd ./projects
$ pwd
/home/user/projects

 

../ refers to the parent directory of your current working directory. The command below will change your directory to the parent directory of the current folder.

$ pwd
/home/user/projects
$ cd ../
$ pwd
/home/user

 

 

ls

The ls command allows you to list the contents of the current directory.

$ ls
Desktop    Dropbox   Public
Documents  Music     Videos
Downloads  Pictures  test.txt

 

By itself, ls will provide you with what you are looking for most of the time. If you need additional information, such as permissions of the files, use the -l option.

$ ls -l
drwxr-xr-x 1 user users 136 Jan 22 10:34 Desktop
drwxr-xr-x 1 user users 308 Feb 14 08:52 Documents
...
-rwxr-xr-x 1 user users   1 Mar 10 20:45 test.txt

 

Hidden files, filenames starting with a dot, are excluded from the output of ls. To include hidden files as well, use the -a option. This will print out all files in the current directory including hidden files in the long format.

$ ls -a
.bash_history  Desktop    .gnupg
.bash_logout   Downloads  .java
.bash_profile  Dropbox    Music
.bashrc        .gnome     Pictures
...

 

The first column shows the permissions of each file. The very first character can be either a - or d. This lets us know if the file listed is a directory, d, or file, -. The next nine characters refer to the permissions of the file, grouped in sets of three. The first set of three permissions is for the owner, the second is for the group, and the third is for everyone else. Each grouping consists of three characters, rwx. Each letter stands for the permission granted, r for read, w for write, and x for execute.

The second column listed by ls -l is the owner. Column three is the group. The fourth column is the size of the file. The remaining columns, excluding the last, is the date and time the file was last modified. Finally, the last column is the name of the file being referenced.

 

 


 

The Developer Basics

We dive now into commands that most developers find useful. This is not to say these commands are not useful to the normal user, but they tend to be used more frequently by developers and system administrators. There are plenty of other useful commands as well, but the selection below represents those most frequently used.

 

find

The useful tool, find as the name suggests, finds files based on some parameters. By itself, find will list all the files in the current working directory including subdirectories. You can also specify the directory in which to run the find command on as shown in the below command that will list out all files in the Project folder of the current user.

$ find ~/Project
/home/user/Projects/test
/home/user/Projects/test/test.txt
/home/user/Projects/index.html

 

An optional argument -name will allow you to search for files with a specified name.The command below will list all files with the name data.json in the current user’s project directory.

$ find ~/project -name data.json
/home/user/project/data.json
/home/user/project/extra/data.json

 

Wildcards, such as the * character can also be used in the name of the file being searched for. The following command will locate all .png files in the current working directory and all subdirectories. The . refers to the current directory.

$ find . -name *.png
./img/car.png
./img/people.png
./pane.png

 

The above command will only match files ending in .png but not .PNG. To match disregardless of letter case, use the -iname argument as in the following command. Including the -not argument will invert the search match listing all files that do not match the search pattern provided.

$ find . -iname *.png
./img/car.png
./img/dart.PNG
./img/people.png
./img/zebra.Png
./pane.png

 

 

grep

The grep command is used to sort through input and locate matching patterns. Supplying a pattern and file, grep will locate each line in the specified file containing the pattern. Common optional arguments include the following

-i for ignore case
-v for invert match
-n for line number

The command below will return all lines that do not include hello from the test.txt file with the appropriate line number.

$ grep -ivn hello test.txt
2:I just saw a cat!
3:The cat was eating a bat.
4:No, not a bat but a nat.
5:And the nat did not get away.

 

Regular expressions can be used in the pattern to search for. We will not go over regular expressions in detail here, but a quick Google search can provide you with a number of resources on the topic. Brackets [] around a set of characters will match any single one of the supplied characters. The following will return all lines that contain bat, cat or nat in text.txt file.

$ grep [bcn]at test.txt
I just saw a cat!
The cat was eating a bat.
No, not a bat but a nat.
And the nat did not get away.

 

Adding a ^ to the beginning of the character list inside the brackets will match anything except the characters inside the brackets. The following will return all lines that contain bat, nat, etc., but will exclude those containing only cat.

$ grep [^c]at test.txt
The cat was eating a bat.
No, not a bat but a nat.
And the nat did not get away.

 

A dot will match any single character. The following will match any line containing food, feed, fffd, etc. in the test.txt file.

$ grep f..d test2.txt
feed
food

 

Using anchors in grep, you can specify if a line should start or end with a specific string.

^string will match any lines beginning with string.
string$ will match any lines ending with string.

$ grep ^Hello test.txt
Hello there!
$ grep away.$ test.txt
And the nat did not get away

 

 

ssh

Secure Shell or ssh allows you to authenticate, connect, and execute commands on a remote computer through the command line. It is one of the most important commands to know as a web developer. To connect to a computer with ssh enabled, open your terminal and type in the following command.

ssh username@servername-or-ip

 

The default port for ssh is 22. If ssh is setup to accept connections on a different port, use the following command to connect.

ssh -p port username@servername-or-ip

 

You will need to enter the user password once the connection has been established. Once connected you will have control of the remote computer and will be able to run commands as needed. You can optionally use ssh keys to authenticate your connection to the remote computer. ssh keys provide more security than password authentication. To create an ssh key, follow the below steps.

  1. Generate a new ssh key:
    ssh-keygen -t rsa
  2.  Enter file in which to save the key (/home/username/.ssh/id_rsa):
    press Enter
  3.  Enter passphrase (empty for no passphrase):
    Enter a passphrase or press Enter for no passphrase
    The passphrase provides an additional level of security. You will need to enter the passphrase each time you connect to the remote computer. On Linux, many distributions contain a utility called ssh-agent which will save the passphrase securely, removing the necessity to re-enter the passphrase each time you connect. If you have ssh-agent running, add the ssh key:
    ssh-add ~/.ssh/id_rsa
  4. Copy the public key to the remote computer.
    ssh-copy-id username@servername-or-ip
$ssh-keygen -t rsa
Generating public/private rsa key parr.
Enter file in which to save the key (/home/user/.ssh/id_rsa): [press Enter]
Enter passphrase (empty for no passphrase): [enter passphrase or press Enter]
Enter same passphrase again: [enter passphrase or press Enter]
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Spq1OI9/EGFEsQBJexCr65/alWdz/nrVw++7B38BGw user@linux
The key's randomart image is:
+---[RSA 2048]----+
|==o+.            |
|..=.. .          |
| ... . .         |
|. .     .    .   |
|.     oSS.    E  |
| .  .*=o+ .  +.. |
|.   ==o+ .  o oo.|
|. . o+  o  ....oo|
| oo+..o..o+ .+...|
+----[SHA256]-----+
$ ssh-copy-id username@servername-or-ip

 

You can now connect to the remote computer through ssh without your password. If you did use a passphrase you will need to enter that if you are not using ssh-agent or another method of storing passwords such as a keychain.

 

scp

Secure Copy or scp is used to copy files from one computer to another securely. It works similarly to the cp command used to copy files locally on your computer. From your local computer, the following command will copy test.txt located in your home folder to /home/username folder on the remote computer.

$ scp ~/test.txt username@servername-or-ip:/home/username

 

To copy a file from the remote computer to your local computer, use the following command where /path/to/file is the location of the file or files and /dir/to/save/to is the destination directory to copy the file or files to.

$ scp username@servername-or-ip:/path/to/file /dir/to/save/to

 

You can even use scp to copy files between to remote computers as shown below.

$ scp user1@servername1:/path/to/file user2@servername2:/path/to/file

 

 

git

Git is another extremely usefully utilities that you will need to use as a developer. Although there are other version control systems available, by far the most popular is Git. If you currently use another version control system, it will still be to your benefit to learn the basics of Git in order to contribute to projects that do use git, whether those projects are open source based or work related. Before you start using Git, you should set up your username and email within Git to allow it to properly label you commits.

$ git config --global user.name "Your Name"
$ git config --global user.email "Your Email"

 

Creating a new repository for Git is easy. Move to the top level directory of your project and initialize the directory as a Git repository.

$ cd /path/to/project
$ git init
Initialized empty Git repository in /path/to/project

 

If you would like to work on a project from another location, such as one on github.com, use the clone command to make a local copy of the specified project, in this case a Rabit Hunt game project.

$ git clone https://github.com/bmb330/Rabbit-Hunt.git
Cloning into 'Rabbit-Hunt'...
remote: Counting objects: 86, done.
remote: Total 86 (delta 0), reused 0 (delta 0), pack-reused 86
Unpacking objects: 100% (86/86), done.
Checking connectivity... done.

 

Once you have initialized or cloned a project, you can view the status of the project files using the status option, which can provide information on modified, new, and deleted files.

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

 

To add files to staging in Git, use the add option. You can add individual files, multiple files or all files.

$ git add script.js
$ git add index.html script.js
$ git add .

 

To commit your changes in staging to the project, use the commit option. Adding the -m option to commit allows you to provide a commit message on the command line.

$ git commit -m "short description of this commit"

 

To push your changes to a remote repository, you will use the push command. To push back to a remote repository labeled origin use the command below. Origin refers to the original remote repository, for instance if you cloned your project from github.com it would refer to the cloned project. You should only push to your github.com repository using this method. If you wish to submit patches to another project, fork the project on github.com, clone the project to your local machine, commit changes back to your fork, then create a pull request on GitHub.

$ git push origin master

 

 


Final Thoughts

With these few commands above, you are well on your way to a solid understanding of some of the most useful developer tools available to you. If you have any suggestions for commands you find useful, please leave a comment below with an example use case. Also, feel free to sign up for the LinuxMaster.me Newsletter to receive updates on new posts and upcoming projects.

 

 

Published by Brandon

Software Developer and Computer Science Student

Leave a comment

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