Snippets Collections
# check cuurent swap space
sudo swapon --show
free -h

# check available disk space
df -h

# create swap file
sudo fallocate -l 1G /swapfile

# verification
ls -lh /swapfile

# enable swap file
sudo chmod 600 /swapfile
ls -lh /swapfile

# mark file as swap space
sudo mkswap /swapfile
sudo swapon /swapfile

# verification
sudo swapon --show
free -h

# make swap file permanent
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# adjust swappiness
cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=10

# set to automatically restart
sudo nano /etc/sysctl.conf

# set cache pressure
cat /proc/sys/vm/vfs_cache_pressure
sudo sysctl vm.vfs_cache_pressure=50

# make permanent
sudo nano /etc/sysctl.conf
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo apt-get update
sudo apt-get install python3-certbot-nginx 

sudo certbot --nginx
sudo certbot --authenticator standalone --installer nginx --pre-hook "service nginx stop" --post-hook "service nginx start"
sudo service nginx restart

crontab -e 
0 0 */1 * * certbot renew

cat ~/.ssh/
sudo service postgresql start
sudo service nginx start

sudo su postgres
# create database

nano .env
yarn install
yarn knex migrate:latest
yarn knex seed:run
forever start index.js
sudo apt-get update && apt-get upgrade

curl -sL | sudo -E bash -
sudo apt-get install -y nodejs
sudo apt-get install build-essential nginx htop git curl postgresql postgresql-contrib ranger

sudo npm install -g forever
sudo npm install -g yarn 

sudo apt install redis-server
sudo service redis start
//Basic - Variables, Constant. 

- Project  - package1 ( first letter should be lower case ) - class1 - Class2
           - package2 - class1 - Class2

//Import Statements:  
- To import the class from different package.
 > import projectName.packageName.className; ( Address )

//Class Declaration:
> public class Sum {    }
// 'public' is access modifier(who can access this class)

//Main method: ( Entry execution point )
package packageName; //Current package name.
public class Sum {  //Access modifier.
   public static void main(String[] args){ 
     //This is basic structure

//Variables | Constant
> dataType variableName;
> dataType variableName = "Value depending upon data type";

  //Primitive Data types examples: 
    int numVar = 10; 
    int numVar;
    numVar = 90000; 
    float fltVar = 10.34f;
    String strVar =  "Singh";
    char chrVar = 'J';
    boolean boolVar = true;
    int a,b,c; //Multiple declarations.
    a= 10;
    b = 30;
    c = 345;

> final int b;
// Once 'final' has been declared, We can not change the 'b's value. (It's constant now.)
public static void main(String[] args) {
 //Basic set up.

//Print in the console.
System.out.println("Printing String...");

- Pink letters are keywords. ( public, static, class, void... )
- Compiler will always start with the 'main' mathod.      
- use ';' after each line of code.
- 'void' is the basically how we tell that we returning nothing. if we want to return a number? then mention 'int' instead of 'void'.                              
int a = 10;
// 'int' is Integer.

String name = "Karan";
// 'String' is string.    
             // Transfer data/methods within classes.
  public class Parent {
   // This is the parent Class.    
    public static void main(String[] args){
     Methods m = new Methods;
     //Methods is the class name.
     // 'm' is the oject.
     // 'm.' will provide 'built in' and custom methods             available in the 'Methods' class.
     // It will return 'Done Amigo' as programed in method. 
 publick class Methods {
    //This is the 'Methods' class ( child class)
   // We won't be using 'main' method here as we are just            sending the data.
     public void ValidateHeader(){
      //Example of an Method.    
      // 'void' since we are not returning anything. 
     public String ValidateFooter(){
      //Example of an Method.    
       // 'String' as we are returning string
        return "Done amigo"  
     public int ValidateFooter2(){
      //Example of an Method.    
        return 200;  

//Java Installation

// Eclipse Installation
> 'New Java Project' 
- src > 'New Java Class'
 - Download Selenium Jar file for Java.
 // Adding 'External Jar' ( Downloaded Selenium exe files ) to the Project Properties. ( As Class not Module )  ( ProjectName => Properties => Libraries ), Which will be used to import methods used in project.
 * Need to do for every project.
 // ''   ( Java API for Selenium )
//For Each browser we need different 'Invoke' file.
 System.setProperty(key, value );
  key = '' ( It's provided by the respective browser developers, Will be different for each browser  )             value = 'Address of invoked file on PC'    
// Create new object.
 className driver = new className();
/* driver: is object
 new : creates new memory for the class */


//                       Basic set up;
  		//Invoking .exe file from Google Chrome 
		System.setProperty("", "C:\\Users\\jpann\\Downloads\\Don't Delete\\chromedriver.exe");
		//Creating Object.
		WebDriver driver1 = new ChromeDriver();

// Invoking for FireFox.
    System.setProperty("webdriver.gecko.driver","Location of           firefox invoke file.")
      //Creating Object.
		WebDriver driver1 = new FirefoxDriver();

          /*   WebDriver Methods.  
//Creating Object.
WebDriver driver1 = new ChromeDriver();          

//Pass the URL to open. 

//Return URL
//Return the Page Source.

//This can be used to navigate the browser ( Go to next or previous link )

//Once the execution is over, Close the test. (current window)

//Once the execution is over, This will close all the Child Windows.

   /* Locator Techniques & Tools used to identify Objects.  
 //Locators: ( the 'selector' is called 'Web Element in Selenium' )
 driver1.findElement("id_NameHere")); //Will locate using 'id'.
 driver1.findElement(By.className("class_NameHere")); // Will locate using 'class name',

// Will locate the element using Tag Name.

 driver1.findElement(By.linkText("forget password?"));
//It will locate the element by the exact text present in the tag.

//Sending Data to an element ( To Input Field ),
 driver1.findElement("id_NameHere")).sendKeys("Text is added from Selenium.")

//It will get the text from #text

- ID's with Numerical values might be dynamic. It might change with clicks/time. So avoid selecting such tags using ID
- Classes with spaces won't work. ( Compound classes will not work )
- If there are two same ID's Selected. It will select the first one.

 //This will click the button with class 'buttonPlay'

 // xpath

> Inspect (F12) on any selected element > Right click on HTML  code on right side ( on the element) > copy > XPath.
> This xpath can be used to select the element.
> This is not always 100% accurate.
> Double quotes inside the double quote won't work. ( use single quotes inside.)
> If the xpath starts with "html/body...", Then it is not relialble to use the path. 
> Might be different path for browsers.  
> Can be created in number of ways. ( using tag/class/attribute/id...)

> Before running the Scipts, We can validate the 'xpath' first, It will save time.
  - We can check/validate the xpath manually by running 
    > $x("xPathHere...") ( It should be written in browser's console, if it returns a array/object then it means the path is valid, if it show null then it's incorrect path)
  - Other way to check the path is to use a extension on the browser.                       
                   > Customized xpath 
 syntax:   //tagName[@attribute='value']
  /*for example */
 - //div[@id='box1'] ( double forward slash are part       of the code, Not comments)
 - //*[@id='username']  
   /*  Here it will  select any tags with id 'username' ( '//' is part of the code, not comments ) */
           > Creating xpath using Regular expression:
 - Sometimes in attributes the value string is fixed but the numerical values keep on changing, or if the value is too long but we know the format So in that case we can use syntax:


Example: <input id="username123"> </input>
> //input[contains(@id,'username')]
 // CSS selector
- CSSselector is 10 times faster than xpath.
> Inspect on any selected element > Right click on HTML  code on right side ( on the element) > copy > CSS selector.
> We can check/validate the path manually using ( in the browser console)
     $("Path here...")

- Css Customized selector:
tagName[attribute='value']   ( @ and '//' are not used here like xpath )

- CSS regular expression selector:

Example: <input id="name1233"> </input>

- Searching using Text
- Syntax : [class='class1 class2']


  // Traversing Through Elements

 // -parent-child
>  If there is no way to select the given element, We can select this tag using it's parent tag.
- define the xpath for parent and then direct to child using tagNames. 
Example: You want to select a 'input' tag and there is no unique/stable way to do it.
- Select it's parent tag first and then come to the child using tagNames, If on the way we have 2 same sibling tags then mention the number with it ( div[1] or divp[2] ).

  - parent : "//div[@class='1st-c']"

> Reach to Child using the parent now
- //div[@class='1st-c']/div/div[2]/div/input
-  parentTag/childTag/innerChildtag  

Child > Parent: ( only possible in xpath)

Example :
child: "//li[@id='item-1']"
- "//li[@id='item-1']/parent::ul"

  //Relative and Absolute xpath.
- Relative : Does not depend upon the Parent or the child node. Even if the parent/child tag is removed, Still the locator (Selected element) should work just fine.  
 Example : "//div[@id='username']"

- Absolute : Here the selector is depended upon the parent/child tags. if any change in the order ,then selector will be affected.
Example:  //section/div/div/div/div/ul/li[2]

      //Sibling Traversing ( "following-sibling::" )

- How to select/traverse through the siblings.

> "//li[@id='li-1']" ( This is the selected 'li' and we want to select it's 3rd sibling.) 
> "//li[@id='li-1']/following-sibling::li[3]"

    //Locating using 'text'  ( using xpath )  
Syntax: "//*[text()=' specificWord ']"
// '*' It represents any tag can be selected.                      
> driver1.findElement(By.xpath("//*[text()=' Singh ']")).getText();                      
//The word should be exactly on the HTML, Include spaces both sides if there are spaces on the HTML code.                      
   /* Selenium Web Drivers
//SELECT :                      
// >Static Dropdown: How to select  option from dropdown list.      
> Select sElement = new Select(elementLocation);
// 'Select' is the in-built class to manage 'select' element.
- We can choose 'option' in 3 ways.
 > sElement.selectByValue("JPY");
 > sElement.selectByIndex(3);
 > sElement.selectByVisibleTest("CANADIAN DOLLAR");

> sElement.deselectAll(); //Will de-Select all the options.

> Thread.sleep(time);
- We can use this to wait for the webpage/Program to laod, So as the next line codes can be executed after 2 seconds.

//Dynamic Dropdown.
- If there are two elements with exactly the same path, It will only select the first one.
- To select the second one, use ("(//a[@value='DEL'])[2]"));
- This will select using it's index.    

: It's not alway good idea to use index, So we use 'Parent-Child' locator,
- So Select the Parent Tag first and then it's child ( This way even if there are two elements with same name, But there Parent could be different.)

Example" ( 1 space after the Parent Element and then the child element Xpath. ):
( //input[@id='ctl00_mainContent_ddl_destinationStation1_CTXT'] //*[@value='DEL'] )
//AutoSuggestive Dropdown.  
: When user type something, The input field will provide some autoSuggestive results ( google, youtube...)

: To Clear the Pre-populated data OR sometimes we just select on the input field and it clears the data.
> .selector().clear();
> .selector().click();

: Use 'Down arrow' button and select using 'Enter'
> .selector()).sendKeys(Keys.DOWN);
> .selector()).sendKeys(Keys.ENTER);

: We can use 'selector' into an variable and re-use it multiple times.
WebElement element = drivere.findElement("idName"));
element.sendKeys("New Text To Seach");
element.sendKeys(Keys.ENTER); //This will push 'Enter' button.

//Radio Buttons:
- We can select button using the usual 'WebElement' 
- we can use  '//input[@name='group1']' to check/compare/code/test the size of the Inputs with same group name.

- Here is the example to select inputs of same group using it's index.
> driver.findElement(By.xpath("//input[@name='group1'][1]")).click();
> Thread.sleep(1000);
> driver.findElement(By.xpath("//input[@name='group1'][3]")).click();
> Thread.sleep(1000);
> driver.findElement(By.xpath("//input[@name='group1'][2]")).click();

- It will return the Size of the input with same same group name.
> driver.findElements(By.xpath("//input[@name='group1']")).size()
> driver.findElements(By.xpath("//input[@type='radio']").get(0);
//It will select the first element.                     

//Play with Attributes:
> selector.getAttribute("value");
> selector.getAttribute("name");
> selector.getAttribute("id");
> selector.getAttribute("class");

//Check the size of the input radio button with same group name.
> int count = driver.findElements(By.xpath("//input[@name='group1']")).size();
> for (int i = 0 ; i < count ; i++ ) {
 //Print the 'attribute's Value of name = 'group1'. We are using loop and it's findElement(s).`
> String checkText = driver.findElements(By.xpath("//input[@name='group1']")).get(i).getAttribute("value");
> if(checkText.equals("Milk")) {
> System.out.println("Milk Found: "+ i);							 driver.findElements(By.xpath("//input[@name='group1']")).get(i).click();

                   /*--------  */

/*  Java Alerts  */
: How can we manage the pop ups which are not web based element's. ( Which are not coded through HTML/Css/Js) are coded through 'Java'.

//We need to switch from 'web' to 'popup' View,So we can manage popups.
> driver.switchTo().alert().getText(); //This will return the whole 'text'on the PopUp.
> driver.switch().alert().sendKeys("Karan Singh"); //This can be used to Pass the value in the text field on PopUp.
> driver.switchTo().alert().accept(); // 'accept' will indicate as:'OK'|'agree'|'accept'
> driver.switch().alert().dismiss(); // 'dismiss' will indicated as 'cancel' | 'No' | 'Ignore'.

                   /*--------  */

//Check Boxes.
> ("//input[@type='checkbox']")
 - It will return all the checkboxes on the given web page. ( use findElements )
> selector.isSelected(); //It will tell if checkbox is selected or not.

                   /*--------  */

- It is a way to check if the Test case Passed or Failed. We are not to use console log's to check the results and see if the test is passed or failed, In work we are to be use "Assertions", Which will automatically tell if a test passes or failes. 
- Download 'testing Java' file and add it to your project Path.

- Boolean Check:
> Assert.assertTrue(data);
//This will expect a TRUE value to Pass the test.

> Assert.assertFalse(data);
//This will expect a FALSE value to Pass the test.

- Value Check: (String or value):
> Assert.assertEquals(selecter.getText(), "5 Adults");
: This will check the 'text' from selector and compare it to the '5 Adults'.

: We can select the current date using classes/ or some other way.

//Check if the element is enabled or disabled.
> select.isSelected(); //This does not work some times, Because of the website/app. As it might appear it's disabled but the selenium gets confused.
- We can Test/check the specific classed/attributes in the element, Which will tell us if the element is disabled/removed.
> select.getAttribute("style")
//This will return a complete STRING of all the CSS properties.
> select.getAttribute("style").contains("opacity:1"); //True
> select.getAttribute("style").contains("opa"); //True
> select.getAttribute("style").contains("1"); //True
> select.getAttribute("style").contains("opp"); //False
> select.getAttribute("style").contains("1");
//We can check the string by using 'contains' method.

  /* ------------XX--XX--XX---------*/

/*-------Deep Dive Into Function-------------- */

: Format Code & debugging
// This will format the code in the aligned format. 

: Naming Convection
- Class name should always start with capital letter
- Variable should always be in lower case letters.
- Use CamelCase for Variable name.
//set up:


  //It will return the absolute path for current folder.
console.log(__filename);  //It will return the absolute path for current folder  with file name.

// Modeles | Require
let data = require("./script");
/* :> './' will look for relative to current path,
'require(".fileName") Will return the object.'

module.exports = { var1, var2 }
// We can export multiple things/variables.

let { people } = require("./totalPeople");
// It will only return the 'people' variable in 'totalPeople'.

let { people, age } = require("./totalPeople");
// It will only return the 'people' and 'age' variables in 'totalPeople'.

// Also called Destructuring.
let os = require("os");
//Will provide built in Operating System module( object).

//Will return the type of OS ( windows/Linux...);

//It will provide the HOME directory

const fs = require("fs");
 //Built in module, Used to read/write the files. ( FILE SYSTEM )
                       // Reading Files
fs.readFile(('./R/text.txt'), ( error, data ) => {
   console.log("Data: ", data); // It will return a package as a Buffer. 
   console.log(data.toString()); // It will provide the data (text.txt) in readable format.
//'readFile' is an async function and will not block the execution.

                      // Writing Files
fs.writeFile('./R/text.txt', " This is new replaced data,  ", ( ) => {
  //If the address is not valid, It will create the file.
  // It will replace the old data.
  //Since it's Async function, Call back function is required.
  console.log("Data updated");
//'writeField' is an asyn function and will not block the execution.

                      // Directories
    if(err) { console.log("Error: ",err) }
    console.log("Folder created");
    if(err) { console.log("Error: ",err) }
    console.log("Folder Removed");

//Check if specific 'folder' exist or not.
  //Check if 'Resources' folder is there or not.
  //'existSync' is a sync function and will block the code. 

  //Check for folder 'R' using '!'.
    console.log(" R Folder does not exists");

 //Create Folder.
     if(err){ console.log("Issue with creatin Folder") };
     console.log("Folder R created")
}else {
    //If already there, then deleting 'R' Folder
        if(err){ console.log("issue with deleting Folder") }
        console.log("Folder R Deleted.")


                      // Deleting Files        
fs.unlink("./R/text.txt", (err)=>{
    console.log("Issue with deleting File");
    console.log("File has been deleted.")

//We should always check first if 'folder'/'files' exist or not.
  console.log("Folder 'R' does exist");

  console.log("File 'file.txt' does exist");
** //Summary
  //Import Modules
const http = require("http");
const fs = require("fs");

//Creating Server
const server = http.createServer((req, res)=>{})

//Read File.
fs.readFile("./R/blogData.txt",(err,data)=>{ })

//Writing Files
fs.writeFile("./R/newFile4", "To a worm in horseradish, The world is horseradish.", (error)=>{
 // console.log("File Updated.")

//Create Directories.

//Check the Folder/File

//Remove Folder
fs.rmdir("./R/NewFolderCreated",(error)=>{ })

//Deleting File
fs.unlink("./R/newFile2",(error) =>{ })

//Server Configuration.
server.listen(8080 ,"localhost",()=>{});


 //Streams and Buffers.       
 Stream : Start using data, Before it has finished loading. Data will be transferred as 'Buffers'.
                //Create/Read new Stream
let createStream1 = fs.createReadStream("./R/sampleData.txt");
//Address should be mentioned.
/* We can pass the 2nd argument as '{ encoding: "utf8" }', and this we don't have to use 'toString()'.
let createStream1 = fs.createReadStream("./R/sampleData.txt",{encoding:"utf8"});

  //'on' is event listener, 
  //'data' is type of event. ( example 'click','scroll')
  //Every time we get new buffer, This 'bufferData' will be called ( call back function.)
                          //Write Stream       
let createStream = fs.createReadStream("./R/sampleData.txt", { encoding:'utf8'});
let writeStream = fs.createWriteStream('./R/blogData.txt');//if address does not exist, It will create new one.

writeStream.write('First Line Here...'); 
// It will write the provided text in './R/blogData.txt'

  //For every 'buffer' generated, It will passed on to 'writeStream' 
    writeStream.write("Some Data");
    writeStream.write( buffer );
 writeStream.write('Last Line Here....'); 
  //Streams and buffers.
let createStream = fs.createReadStream("./R/sampleData.txt", { encoding:'utf8'});
let writeStream = fs.createWriteStream('./R/blogData.txt');

writeStream.write("First Line...");

//Using 'PIPE'
 //It will automatically pass all the data to './R/blogData.txt'. from "./R/sampleData.txt".
                 //Client and Servers
const http = require("http");

const server = http.createServer((req, res)=>{
      console.log("Request Made")

server.listen( 3000 , 'localhost' ,()=>{
  // 'localhost' is by default.
    console.log("Server is Live on Port 3000")

            //Requests and Responses.
  const server = http.createServer((req, res)=>{
      console.log("Request Made")
    //It will provide the 'url'. Root url is '/'.
    //It will return the method used. 

const server = http.createServer((req, res)=>{

  //Set Header Content Type.
  res.setHeader("Content-type", "text/plain");
  //It will tell browser what kind of content to      expect. It can '"text/html"', If we want to pass     on HTML content/tags. 
  res.write(" Hello Karan");
  res.end(); //Manually end it. This will send the response to the browser. 
//Linking HTML file to the Code. 
 let fs = require("fs");

const server = http.createServer((req, res)=>{

  res.setHeader("Content-type", "text/html");
  //'text/html' is used, This time we will passing data as a HTML content ( with Tags nd all);
  fs.readFile('./home/Index.html',(err, data)=>{
      console.log("Koi Panga", err);
      //If err then we want to end the response, So that browser will move with next step ( other wise it will struck on loading )
    }else {
      res.write(data); //We are passing 'index.html' as the data.
      //We can also use 'res.end(data)'(for single file). ( res.write() will not be needed. )

  res.write(" Hello Karan");
  res.end(); //This will send the response to the browser. 
 const server = http.createServer((req, res)=>{   
 console.log("URL: ", req.url)
 let path = "./"; // Root will always be './'
 switch( req.url ){
  case '/':
  path += 'index.html'

  case '/about':
  path += "about.html";
  default :
  path += "404.html";
     //This we can add specific page

 //Header Content.
 res.setHeader("Content-type", "text/html");
 fs.readFile(path,(err, data )=>{
   //Depending upon the URL, It will return the required HTML/plain page.
                  //Status Codes
   200 - OK
   301  Resource moved
   404  Not Found
   500  Internal serval error



/*  Creating Database  */
           /* Common Commands */

man //It is the 'manual' for all the commands in the linux system. 
> man ls //It will provide manual for 'ls'
> man touch //It will provide manual for 'touch'
> man man (All the manual will be displayed)
> man -k search //It will provide all the keywords related to 'search'.
> man -k jaskara //It will provide all the keywords related to 'jaskara'

which //It will provide the location from where shell is using the command.
> which touch //It will return the location of 'touch' cmd.
> which ls //It will return the location of 'ls' cmd.

 uname // This cmd will provide the system OS basic information.
uname -a | uname -i | uname -m

sudo parted // "Hard drive" details
parted -l //Provide partition of the HDD

sudo shutdown -h now //It will immediately shutdown the system
sudo shutdown -h +10 //It will shutdown the system in 10minutes.   
sudo shutdown -h +10 "System Will shutdown in 10minutes, Please Save your Work"//It will shutdown the system in 10minutes with the Prompted information.   
sudo shutdown -r now //It will Reboot the system.
sudo shutdown -c // To cancel the scheduled shutdown. 

pwd //Print Working Directory. ( It will provide the current directory)

cd //Change directory.
> cd /  //This will take to the parent directory.
> cd /childFolder/ChildsChildFolder/ // This will take the folder. But we should be in the current node to get to the child.   
> cd ~/desiredFolder //It will directly take to the desired folder. We don't have to worry about the current node.
> cd ..   //It will take to the previous directory
> cd ../..  /* Will take two directories back*/
> cd ../../..  /* Will take three directories back*/
> cd ~ //It will take to home directory

ls // It will Provide all the list items/files in the relative directory
> ls -l // It will provide detailed information.
> ls -alh  
> ll
// It will provide easier format to read.
> ls test* //It will only look for folders starting with string 'test'.
> ls *est //It will only look for folders ending with string 'est'.

> find / -name fileName* //it will find evrything starting          with 'fileName'.( might have to add sudo )
mkdir //It is used to create new folders. 
> mkdir folderName1
> mkdir test{1..5} //It will create 5 folders with pattern test1...test5.
> mkdir test{a..d}
touch // It will create new File(blank) in the directory.
> touch index.html
> touch script.js
> touch index.html style.css script.js //It will create all three files.

mrdir //It is usded to delete folders.

rm //It is used to remove files/Folders.
> rm index.html
> rm index.html style.css script.js //It will remove all three files.
rm -r folderName //Will delete all child data ( 'r' is recursive )
> rm -r test{1..5} //It will remove all the files with provided pattern

cat //Concatenate FILE(s) to standard output.
    //It can also be used to view files/data
    //It can only view text files.
> cat text.txt // It will print the 'text.txt'
> head text.txt //It will display the first 10 lines of the 'text.txt'
> head -2 text.txt //It will display first 2 lines.
> tail text.txt //It will display the last 10 lines of the 'text.txt'
> tail -2 text.txt //It will display last 2 lines.

> cat fileName (press double 'Tab') //It will return all the files starting with 'fileName'(s)

 grep //...
     //This can be used to filter data.
> sudo grep opened /var/log/auth.log //It will provide all the 'opened' in 'auth.log' file.

date //It will return date information.


                 /*General Theory */
- Linux is case sentitive
- Relative : Present location ( Current directory)
- Absolute : Location from Root.
- Sudo group : A group of superusers that can access the root account and be receive unlimited privileges.


              /* Ubuntu Server */

> sudo updateddb //It will update the database.

> locate fileName 
> locate test* //It will return all files starting with 'test'  

              /*  Managing User */
//ONLY super user can add user on the system.
 //To Add User.  
> sudo useradd -d /home/dUserFolder -m dUserName
//It will add 'dUserName' as a new user name on the system
> sudo passwd dUserName
//It will create the password for 'dUserName'.

//2nd way to Add User. ( better way )
adduser //It is a script to 'add user',(not a command)  
> sudo adduser dUserName
//It will automatically create user and it's respestive folder and will ask to create password for it.

> cat /etc/group
 //It will return all the groups on the system. 
> cat /etc/group | grep dUserName
//It returns the 'group'(s) of user name 'dUserName'


              //Modify Users

//Add Group to user.
sudo usermod -aG groupName UserName
> sudo usermod -aG sudo dUserName
// We are adding 'sudo' group to user 'dUserName'.

> su UserName1
//It will change the terminal to 'UserName1'

//Lock User
> sudo usermod -L dUserName

//unlock User
> sudo usermode -U dUserName

//   /etc/passwd
> cat /etc/passwd
 //It will provide all the user's on the system ( including system groups ).

> sudo vipw
//It will display all the User's in a nano editabled list.
// Remove the need groups by using CTRL+K(To remove the line/group ) > CTRL+O (over write) > CTRL+X (exit).
//Removed groups will not show in the '> cat /etc/passwd'

//2nd way to remove group
> groupdel [options] GROUPNAME

//  /etc/shadow
//It will return all the user's and there respective password and password data ( encryption used + Password expiration information ) . 

//Remove User
> deluser [--remove-all-files] [--backup] [--back-to DIR] dUserName
//It will remove the user and also the create the back for it.


            /*   Managing Groups  */

> sudo addgroup groupName1
//It will add 'groupName1' to the user.

> grep groupName1 /etc/group
//It will return the information about 'groupName1' 

> groups
//It will return all the groups for the user.

> ll text.txt  
> ls -alh text.txt
 //It will provide the basic information about the file, inclduing permissions it has. 

-1 - 2- 3 -4
//Here Numbers are different groups. 
rw : read and write
r : Read.
x : executable file

To change Groups:
> sudo usermod -g newPrimaryGroup dUserName
//'newPrimaryGroup' Will be the primary group.

//Where can we keep the files to share data between different users. 
/srv - for files that may be shared using a service externally.

//To modify the permission for user on the group.

//It will make new folder,
> sudo mkdir /home/newFolder

 //Adding new group
> sudo addgroup grpName1

// Group 'groupName1' will have access to 'newFolder' folder.
> sudo chgrp grpName1 /home/newFolder


           /*  Managing Text Files  */

vim | nano
//Two popular linux terminal's IDE.

// VIM

> sudo app install vim
//In case if VIM is not installed by default.

> vim filesName.text


     /* Linux Structure */

- man hier
//It will return the structure of the Linux system and basic idea about all the files.


         /*  Remote Access    */

- SSH works on TCP.



# By default, each destination (name of new link) should not already exist

ln -s /home/user/project /var/www/html

# The link will be created inside /var/www/html having the name of the target i.e. project.
# If you want to have a symlink /var/www/html pointing to /home/user/project then you should not have the directory html present beforehand. So, you should only have /var/www and then running the following will create the desired symlink (don't do this unless you are sure)
command -v STM32_Programmer_CLI >/dev/null 2>&1 || { echo >&2 "Need to add STM32_Programmer_CLI to the enviorenment path. Aborting..."; exit 1; }

if [[ $file =~ \.bin$ ]] || [[ $file =~ \.hex$ ]]; then
    echo "OK" >&2
    echo "NOT OK" >&2
    exit 2
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 Path to binary file" >&2
  exit 1
sudo apt install stress
stress --cpu 8
curl -fsSL | sudo -E bash -
sudo apt-get install -y nodejs
# check the status of the web server i.e apache2
sudo systemctl status apache2

# restart the service
sudo systemctl restart apache2

# return network-related information using a combination of flags along with the netstat command to check which process is using a particular port
sudo netstat -nlp

# find python3 programs running
ps -ax | grep python3

# kill a process by its process ID (PID)
sudo kill [process-id]

# let's check for the availability of any service with the keywords "python" or "jimmy"
sudo systemctl --type=service | grep jimmy

# stop and disable a service using
sudo systemctl stop _servicename_ && sudo systemctl disable _servicename_

# start a web service using nginx
service nginx start

# check nginx landing page using curl
curl http://localhost:80
# install docker
sudo apt-get install

# create and run a container from an image from the Docker Hub
sudo docker run --name firstContainer ubuntu:latest # where firstContainer is the name of the container

# list locally available docker containers
sudo docker ps -a

# open a docker container in interactive mode in the terminal
sudo docker run -it --name myContainer ubuntu:latest # where myContainer is the container name
# you can exit the container by pressing CTRL+P and CTRL+Q

# attach container to terminal
sudo docker attach myContainer # the container will now stay open in the background even after exiting via CTRL+P and CTRL+Q

# execute commands in the container running in the background
sudo docker exec myContainer echo $PATH

# delete containers
sudo docker rm -f firstContainer myContainer

# create new docker image based on your local environment/container
sudo docker commit myNginx docker_id/image_name # where myNginx is the name of your currently running container

# create new docker container from an image from a previously committed image
sudo docker run -it --name nginxNew docker_id/image_name

# list images on your machine
sudo docker image ls

# login to your docker hub account from the terminal
sudo docker login # you will be prompted to enter your id and password

# push an image to docker hub when logged into your docker account
sudo docker push docker_id/image_name

# run a docker container in the background
sudo docker run -d --name myApp nginx

# start an interactive bash terminal for the container running in the background
sudo docker exec -it myApp bashapt-get

# stop a running container
sudo docker stop myApp

# start a stopped container again
sudo docker start myApp
# replace _file_name_ with the name of the file that is to be made executable including its filetype suffix, e.g. ".py"
chmod +x _file_name_
sudo forever start --sourceDir /opt/bitnami/projects/nesk_back -c "npm run prod" /
ip addr | grep eth0 | grep inet | awk '{print $2}' | awk -F '/' '{print $1}' | awk '{printf "%s:3000", $0}' | clip.exe

Tue Sep 21 2021 17:41:17 GMT+0000 (UTC)


Tue Sep 21 2021 17:30:11 GMT+0000 (UTC)


Tue Sep 21 2021 17:17:46 GMT+0000 (UTC)


Tue Sep 21 2021 13:03:29 GMT+0000 (UTC)


Tue Sep 21 2021 12:58:44 GMT+0000 (UTC)


Sun Sep 19 2021 05:45:26 GMT+0000 (UTC)

#linux #server

Mon Aug 30 2021 20:10:30 GMT+0000 (UTC)

#linux #server

Wed Aug 25 2021 04:44:09 GMT+0000 (UTC)

#linux #server

Mon Aug 23 2021 14:59:32 GMT+0000 (UTC)

#linux #server

Wed Aug 11 2021 03:54:23 GMT+0000 (UTC)

#linux #server

Tue Jul 27 2021 03:07:32 GMT+0000 (UTC)

#linux #server

Sat Jul 24 2021 13:41:12 GMT+0000 (UTC)

#linux #server

Fri Jun 18 2021 08:58:12 GMT+0000 (UTC)

#symlink #linux #filesystem

Wed Jun 09 2021 10:26:20 GMT+0000 (UTC)

#linux #shell-script

Wed Jun 09 2021 10:16:48 GMT+0000 (UTC)

#linux #shell-script

Wed Jun 09 2021 08:41:11 GMT+0000 (UTC)

#linux #shell-script

Thu May 06 2021 10:24:14 GMT+0000 (UTC)


Thu May 06 2021 10:20:29 GMT+0000 (UTC)

#linux #cpu

Thu May 06 2021 10:18:48 GMT+0000 (UTC)

#linux #cron

Sun Apr 18 2021 16:35:19 GMT+0000 (UTC)

#ubuntu #bash #linux

Sat Apr 10 2021 05:57:14 GMT+0000 (UTC)

#linux #nginx

Sat Apr 10 2021 05:55:14 GMT+0000 (UTC)

#linux #docker

Thu Mar 25 2021 09:14:28 GMT+0000 (UTC)


Sat Jun 13 2020 08:20:55 GMT+0000 (UTC)

#bash #linux

Fri Dec 27 2019 13:19:35 GMT+0000 (UTC)

#commandline #interesting #windows #ubuntu #linux

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension