Beginner Linux Commands

Summary

  • Dealing with Directories
  • Dealing with Files
  • Getting started with VIM
  • Manage Processes
  • Miscellaneous Commands

Dealing with Directories


mkdir  test -> Creates directory

cd test -> Change directory to test

cd .. -> Navigate to previous directory in the tree

cd - -> Navigate to previous directory

cp -rf test /usr/local -> Copies the test directory and all the content to /usr/local/

mv -rf test /usr/local -> Moves the test directory and all the content to /usr/local/

rm -rf test ->  Deletes test directory

mv test test2 -> Renames test to test2

Dealing with File Content


============================ CAT ======================================

cat test.txt (view contents in a file)
cat -n test.txt (view content with line numbers)

============================ WC =======================================

wc test.txt (view lines, words and characters)
wc -l test.txt (only lines)

============================ HEAD =====================================

head test.txt (get top 10 lines)
head -n 5 test.txt (returns top 5 lines)

============================ TAIL =====================================

tail test.txt will (return last 10 lines)
tail -n 5 test.txt (returns last 5 lines)
tail -f /var/log/messages (live monitoring on what is happening on the system)

============================ LESS ======================================

less test.txt (a simple editor)
/kernel (search kernel key word)

============================ GREP ======================================

grep bash /etc/passwd (searches word kernel in test.txt)
grep bash /etc/passwd /etc/group (search a word multiple files)
grep -e root -e bash /etc/passwd /etc/group
grep bas /etc/passwd -c (number of keywords found)
grep -i bas /etc/passwd (CASE INSENSITIVE)
grep root_file test.txt -w (Search exact word)

============================ CUT =========================================

cut -d : -f 1 /etc/passwd (cuts the row into columns based on delimiter : in this case)
cut -d : -f 1,5 passwd (1 and 5)
cut -d : -f 1-5 passwd (1 to 5)
free -m (view memory usage)
free -m foo.txt (writes the output to file)
cut -d ' ' -f 4 foo.txt4
[limitation of cut: files need to be even and well formatted]

============================ AWK ===========================================

awk '{print $4}' foo.txt (returns only 4th column default delimiter is spaces)
awk -F : '{print $1}' passwd (F-field seperator)
awk -F : '{print $1,$3}' passwd (1 and 3)

============================ SEARCH =========================================
find /root -iname "*.log" - Search for files with .log extension

Getting started with VIM

Quick Options in Vim Editor:


vim /etc/ssh/sshd_config

:set nu - Show line numbers

:set nonu - No line numbers

:set ic - Set Case insensitivity

:set noic - Set No Case insensitivity

yy - copy line

yw - copy word

10yy - copy 10 lines

dd - cut line

10dd - cut 10 lines

dw - cut word

gg - Puts Cursor at Beginning of a File

G - Puts Cursor at End of a File

Insert Mode 


i - Starts at Exact Cursor position

a - Start From Right Next to Cursor position

I - Puts Cursor position at Beginning of a Line

A - Puts Cursor position at End of a Line

o - Puts Cursor position to New line Below

O - Puts Cursor position to New line Above

cc - Puts the cursor by Deleting the Existing Line

Search


:s/root/rootX - Search (Case sensitive) & Replace root with rootX

:2s/root/rooX/gi - Search with case insensitivity and Replace first two search results

:%s/root/rootX/gi - Search with case insensitivity and Replace root with rootX

 

Manage Processes


htop -> list running process

kill 1232 or kill -TERM 1232 or kill -15 1232 -> Terminate process

kill -KILL 1232 or kill -15 1232 -> Force Terminate process

ps -> list all processes

ps aux -> list all processes with details

ps axjf -> list all process with details and tree

kill -HUP 1232 -> Hangup signal reloads config of the process

 

Miscellaneous Commands


arch - Print Machine architecture

cal -Display Calendar

date - Display Date and Time

which java - Display version of Java installed

Beginner Linux Commands

Simple JPA Example

This exampe will use configuration by exception, which means the JPA Provider will map an entity to database using all the defaults.

Build

Create simple app using Maven, refer this post

Dependencies:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.3.0.Alpha1</version>
</dependency>
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.6.4</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.5</version>
</dependency>

Create a POJO Class User,

package com.example;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Created by zillani on 11/26/2016.
 */

@Entity
@NamedQueries({
        @NamedQuery(name = "findAllUsers", query = "SELECT u FROM User u"),
        @NamedQuery(name = "findUserByName", query = "SELECT u FROM User u WHERE u.username=:username")
})
public class User {

    @Id
    @GeneratedValue
    private Long id;
    @NotNull
    private String username;
    @NotNull
    @Size(min = 6,max = 45)
    private String password;
    private String email;
    private String phone;
    private int age;
    private String gender;

    public User() {
    }

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

Create persistence.xml file under resources/META-INF

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">

<persistence-unit name="simple-jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.example.User</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.sql-load-script-source" value="insert.sql"/>
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>

</persistence>

Create sql file under resources

INSERT INTO test.user(ID,USERNAME,PASSWORD,EMAIL,PHONE,GENDER,AGE)VALUES(2,"zillani","root","shaikzillani@gmail.com","9247411984","male",25);
INSERT INTO test.user(ID,USERNAME,PASSWORD,EMAIL,PHONE,GENDER,AGE)VALUES(3,"Humayun","root","humayunsyed@gmail.com","9991234812","male",23);
INSERT INTO test.user(ID,USERNAME,PASSWORD,EMAIL,PHONE,GENDER,AGE)VALUES(4,"Mahesh","root","mahesh.b@gmail.com","9562235658","male",25);

Create a executable class, Main

package com.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        User user = new User();

        user.setAge(25);
        user.setEmail("stranger@gmail.com");
        user.setGender("female");
        user.setPassword("root");
        user.setPhone("9948184406");
        user.setUsername("rh");

        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("simple-jpa");

        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction entityTransaction = entityManager.getTransaction();

        //INSERT USER INTO DB
        entityTransaction.begin();
        entityManager.persist(user);
        entityTransaction.commit();

        // FIND ALL USERS
        List<User> allUsers = entityManager.createNamedQuery("findAllUsers",User.class).getResultList();
        System.out.println("############## ALL USERS ###################");
        for (User allUser : allUsers) {
            System.out.println(allUser.getUsername());
        }
        System.out.println("############## ALL USERS ###################");

        //FIND USER BY USERNAME
        String un = "zillani";
        User foundUser = entityManager.createNamedQuery("findUserByName",User.class).setParameter("username",un).getSingleResult();
        System.out.println("################ FIND USER BY USERNAME #################");
        System.out.println(foundUser.getUsername());
        System.out.println("################ FIND USER BY USERNAME #################");
entityManager.close();
        entityManagerFactory.close();
    }
}

The Following should be the project structure, build the project using mvn clean install,

untitled

Running the main class should insert new Users into the database and verify the retrieved.

Download the example here

Simple JPA Example

Getting Started with git

Summary:

  • Setup
  • Create your first repository and push
  • Commit and push
  • Remote Origin
  • Branching
  • Logging and navigating history

Setup

Local configuration

Local configuration means that your attributes are applicable only within your repository. Configure your username and email using following commands,


git config --local user.name "zillani"

git config --local user.email "shaikzillani@gmail.com"

View: Verify if name and email are set using the following commands, this would print the configured username and email


git config --local user.name

git config --local user.email

Global configuration:

Local configuration means that these variable are applicable for all the git repos on your system by default.


git config --global user.name "zillani"

git config --global user.email "shaikzillani@gmail.com"

This could have also be set by editing .GITCONFIG file located in your root directory, Example for windows: C:\Users\lenovo


[user]

email = shaikzillani@gmail.com
name = zillani

Creating your first Repo and Pushing:

Imagine that you have an empty repository on github.com, whose url is https://github.com/zillani/simpleApp.git, now you have some basic template of your app that you want to push to server, here’s what you would need to do,


git init

git remote add origin "https://github.com/zillani/simpleApp.git"

git add .

git commit -m "initial commit"

git push -f origin master

Note: origin is just a word, you can use any other word say stash-origin or any word

Commit and push


git add .

git commit -m "Added logger"

git push origin master

Remote Origin


git remote -v - Display remote origins

git remote remove origin - Deletes origin

git add remote origin https://github.com/zillani/simple-service-app.git - Adds Remote origin

[Note: origin is just a keyword, any other keyword can also be used]

Branching

View branch


git branch -l
git branch -r

Creating new branch


git checkout -b dev

Shifting

Shift to existing other branch say from ‘master’ to ‘dev’


git checkout dev

Merging branches

Merging dev into master, checkout to master branch and


git merge dev

Deleting a branch

Locally, say deleting dev branch


git delete -d dev

Remote branch,


git push origin :dev

Logging and Navigating history

Check your logs

git log

Check your changes

git status

Navigate back to some old commit

use the SHA1 code of the log, using git log and copy some portion on the SHA1 of the commit and give as below

git checkout u8jedfy667h6359ah77
Getting Started with git