Automation QA Testing Course Content

10 Powerful Command-Line Options of Common Linux Commands

 10 Powerful Command-Line Options of Common Linux Commands

1. cp -p (preserves timestamp)

You have definitely used the cp command to copy files or directories but do you know how to preserve timestamps while copying files or directories? Well, I didn't, at least until a few months ago. The cp - p command will preserve the timestamp when you copy a file. It's very useful, particularly for taking backup while changing files. The timestamp of the backed file is very important for troubleshooting etc.

$ cp - p $file


2. mkdir -p (create directory structure)

I am sure you have used the mkdir command to create directories and sometimes you might have been frustrated also while creating a complex directory structure one by one. You could have saved a lot of your time there if you knew the mkdir -p option which copies parent directories if it doesn't exist.

For example, when you copy a file /app/config/app.properties then it will create those directories automatically if they don't exist.

$ mkdir - p

3. scp -i (file copy without password using identity file)

This is another useful Linux option of a very common command like SCP which I discovered very late. The SCP command is used to securely copy files and directories from one host to another host. 

When you copy files using SCP, it asks for your username and password but if you are doing using script, you better want to do a password-less SCP and that's where scp -i helps. It can use an identity file to copy files from the remote host rather than using your current username. 

The Identity file contains ssh keys which are required to login to the remote host and copy files.

$ scp -i /home/appuser/.ssh/id_rsa_app 
        datauser@host:/app/data/outbound/stocks.xml


Here the identity file: id_rsa_app contains the private/public key for "datauser". The beauty of this option is that it won't ask for a password if you run this command

4. grep -c  (count number of matches)

Many times we are interested in knowing whether the file contains a matching word or not and the grep command just tells you that, but sometimes you also want to know how many times that particular keyword appears in files? I mean, could of the matching keyword. 

That's where grep -c helps. It will tell you the count of the matching keyword.

It's very useful to find details like how many times a user has logged in or how many files he has downloaded, or how many instruments you have received from upstream, and so on. For example,

$ grep -c "keyword" app.log

will print how many times "keyword" has appeared in the app.log file.


5. find -mtime (search files by modified time)

The find command is one of the most powerful commands in Linux and I have spent considerable time learning many useful find command options to improve my productivity. You can find all of them in my earlier post about 10 examples of find command in Linux. 

One of them is -mtime which is a shortcut for modified time and can be used to search files that have been modified recently like in hours or days. This is very useful while troubleshooting to check if anyone touched any important files. For example

$ find -mtime -3

will print the files that have been modified in less than 3 days or in the last three days. You can also search for more than 3 days like using +3 day


6. cd - (takes you to the previous directory)

We all have used cd but do you know how to go to the previous directory quickly? Well, that's what "cd -" do. It takes you to the previous directory. Yes, even without any option cd command is powerful. To be honest, I was lucky to know this item a little be earlier and since then I have been using it almost on a daily basis.

$ cd /home/test1/
$ cd /opt/bin/
$ cd -
/home/test1/


7. pwd -P (shows the actual path for soft linked directory)

This is again one of those basic Linux commands you will learn in your first Linux class but how many of you know this option? Let me ask you another way, how do you find the actual path of a folder which is linked? Well, that's where pwd-P helps. 

Just pwd will tell you the current folder with the path you followed, which could be linked also but pwd -P will tell you the actual folder location as shown in the following example:

$ pwd
/com/unicorn/app/current
$ pwd -P
/com/unicorn/app/1.0.23

8. tail -f (seeing live updates on a file)

This is another useful option for one of the most common Linux commands. If you haven't come across the tail, it is used to see the content of the file from the bottom, and the tail -f lets you see the live updates. This option is particularly useful to see if your log file is moving and what is logged at the moment.

$ tail -f app.log

9. netstat -p (print process id  of the process for connections)

This is one of the powerful Linux networking commands generally used to find the process which is listening on a particular port, but do you know how to print the process id which is listening on a port? Well, that's where netstat -p helps. It prints the process id and name of the program to which each socket belongs. This is useful because you now also kill the process if you don't want to.

$ netstat -nap | grep LISTEN

10. The for loop ( good for automation of repeated tasks)

This is not exactly a Linux command but a basic bash shell construct which allows you to automate some task. For example, if you have your application running on 5 production host and you want to check if they have enough space or not. Instead of going to each host using ssh and checking manually, which would take around 10 to 15 minutes, you can just run this shell script and get this done in seconds.

$ for h in host1, host2, host3, host4, host5; 
do ssh "${h}" "df -h /app/logs"; 
done



How to handle browser level notification using Selenium Webdriver

 

I am Automating some test cases using Selenium Webdriver and core Java,in chrome browser for one test case on clicking button I am getting browser level notification 'Show notifications with options Allow and Block'. I want to select Allow option. Can anyone know how to handle this kind of notifications using Selenium webdriver. please refer following snapshot for more details


For Old Chrome Version (<50):

//Create a instance of ChromeOptions class
ChromeOptions options = new ChromeOptions();

//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");

//Set path for driver exe 
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");

//Pass ChromeOptions instance to ChromeDriver Constructor
WebDriver driver =new ChromeDriver(options);

For New Chrome Version (>50):

//Create a map to store  preferences 
Map<String, Object> prefs = new HashMap<String, Object>();

//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create an instance of ChromeOptions 
ChromeOptions options = new ChromeOptions();

// set ExperimentalOption - prefs 
options.setExperimentalOption("prefs", prefs);

//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

For Firefox :

    WebDriver driver ;
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("permissions.default.desktop-notification", 1);
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability(FirefoxDriver.PROFILE, profile);
    driver = new FirefoxDriver(capabilities);
    driver.get("http://google.com");


Java Interview Coding Challenge


 Problem #1

Consider the Following Problem:

  Write a short program that prints each number from 1 to 100 on a new line.

            For each multiple of 3, print "Fizz" instead of the number.

           For each multiple of 5, print "Buzz" instead of the number.

           For numbers which are multiple of both 3 and 5, print "FizzBuzz" instead of the number.


Solution:

public static void printFizzBuzz(int n) {

for(int i=1;i<=n;i++) {

if((i%3==0) && (i%5==0)) {

System.out.println("FizzBuzz");

}else if(i%3==0) {

System.out.println("Fizz");

}else if(i%5==0) {

System.out.println("Buzz");

}else {

System.out.println(i);

}

}

}

---------------------------------------------------------------------------------------------------------

Problem #2

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

      Given nums = [2,7,11,15], target = 9,

                Because nums[0] + nums[1] = 2 + 7 =9,

                return [0,1] 

Solution:

public class GetTwoSum{

protected static int[] getTwoSum(int[] numbers, int target) {

//create a Map

Map<Integer, Integer>visitedNumbers = new HashMap<>();

for(int i = 0; i < numbers.length; i++) {

int delta = target - numbers[i];

if(visitedNumbers.containsKey(delta)) {

return new int[] {i, visitedNumbers.get(delta) };

}

visitedNumbers.put(numbers[i], i);

}

return new int[] {-1, -1};

}

public static void main(String[] args) {

printFizzBuzz(100);


int[] numbers = new int[] {2,3,7,4,8};

int target = 6;

int[] result = getTwoSum(numbers, target);

System.out.println(result[0] +" "+result[1]);

}


}

===============================================================

Problem # 3

               ReverseString


public class Ch03ReverseString {


public static void main(String[] args) {

String str = "Hello World!";

System.out.println(reverseWithStringBuilder(str));

System.out.println(reverseManually(str));


}


private static String reverseManually(String str) {

// Create object fir StringBuilder

StringBuilder sb = new StringBuilder();

for(int i = str.length() - 1; i >= 0; i--) {

sb.append(str.charAt(i));

}

return sb.toString();

}


private static String reverseWithStringBuilder(String str) {

return new StringBuilder(str)

.reverse()

.toString();

}


}

----------------------------------------------------------------------------------------------------------------------

Problem #4

        Implement a Stack in java


public class Stack {


private int array[];

private int top;

private int capacity;

Stack(int capacity){

this.array=new int[capacity];

this.capacity=capacity;

this.top=-1;

}

public void push(int item) {

if(isFull()) {

throw new RuntimeException("Stack is full");

}

array[++top]=item;

}

public boolean isFull() {

return top == capacity - 1;

}



/**

* Pop will return top item and remove from the stack and update the stack

* @return

*/

public int pop() {

if(isEmpty()) {

throw new RuntimeException("Stack is empty");

}

return array[top--];

}

/**

* peek will return the top item and wont remvoe the item from stack

* @return

*/

public int peek() {

if(isEmpty()) {

throw new RuntimeException("Stack is empty");

}

return array[top];

}



public boolean isEmpty() {

return top==-1;

}

}

-------------------------------------------------------------------------------------------------------------------

Problem # 5

      Reverse an Integer

public class ReverseInteger {


public int reverse(int input) {

int reversed=0;

while(input!=0) {

reversed = reversed*10 + input % 10;

input /=10;

if(reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) {

return 0;

}

}

return reversed;

}

public static void main(String[] args) {

System.out.println(new ReverseInteger().reverse(123));


}


}

-------------------------------------------------------------------------------------------------------------

Problem #6

     Convert from Integer to Roman numeral

    I -->1

  II -->2

 III -->3

IV -->4

V -->5

VI -->6

X -->10

L -50

C- 100

D -500

M -1000

public class IntegerToRoman {


public static String intToRoman(int num) {

String[] thousands = new String[]{"","M","MM","MMM"};

String[] hundreds = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};

String[] tens = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};

String[] units = {"","I","II","III","IV","V","VI","VII","VIII","IX"};

return thousands[num / 1000] +

hundreds[(num%1000)/100] +

tens[(num % 100) / 10] +

units[num % 10];

}

public static void main(String[] args) {

System.out.println(intToRoman(124));


}

-----------------------------------------------------------------------------------------------------------------------

Problem # 7

 Convert Roman numeral to Integer

public int romanToInt(String s) {

Map<Character,Integer>map = new HashMap();

map.put('I', 1);

map.put('V', 5);

map.put('X', 10);

map.put('L', 50);

map.put('C', 100);

map.put('D', 500);

map.put('M', 1000);

int result = 0;

for(int i=0;i<s.length();i++) {

if(i>0 && map.get(s.charAt(i)) >map.get(s.charAt(i-1))){

result += map.get(s.charAt(i)) - 2 *map.get(s.charAt(i-1));

} else {

result +=map.get(s.charAt(i));

}

}

return result;

}

=================================================================

Problem # 8

Longest Palindrome Substring

public class LongestPalindromeSubstring {

 int resultStart;

 int resultLength;

public String longestPalindrome(String s) {

int strLength = s.length();

if(strLength < 2) {

return s;

}

for(int start = 0; start < strLength -1; start++) {

expandRange(s,start,start);

expandRange(s,start,start + 1);

}

return s.substring(resultStart,resultStart + resultLength);

}

private void expandRange(String str, int begin, int end) {

while(begin >= 0 && end < str.length() && str.charAt(begin) == str.charAt(end)) {

begin--;

end++;

}

if(resultLength < end -begin -1) {

resultStart = begin +1;

resultLength = end - begin -1;

}

}

}

----------------------------------------------------------------------------------------------------------------------

Problem # 9:

    Detect Capital

    Given a word, you need to judge whether the usage of capitals in it is right or not.

 Right Usage:

  1. All letters in this word are capitals
  2. All letters in this word are not capitals
  3. Only the first letter in this word is capital   
  • Example:
  • All caps : "USA"     
  •     

public class DetectCapital {

/**
* Approach 1 : The "clever" solution
* Count the number of uppercase letters
* if it is zero or length of string, return true
* if it is not 1, return false
* if it is 1 and the first letter is uppercase, return true
* Time Complexity -- O(N)
* can we do better?
* Disadvantage:
* Quit at the first wrong character
*  valid --AAAAA
*  Valid : aaaa
*  valid : Aaaaa
* @param word
* @return 
*/
public static boolean detectCapitalUse(String word) {
int numberOfCapitals = 0;
for(int i = 0; i < word.length(); i++) {
if(Character.isUpperCase(word.charAt(i))) {
numberOfCapitals++;
}
}
if(numberOfCapitals == word.length() || numberOfCapitals == 0) return true;
return numberOfCapitals == 1 && Character.isUpperCase(word.charAt(0));
}
/**
* Approach 2:
*
*/
public static boolean detectCapitalUse2(String word) {
//Case 1 : All Capitals
int n = word.length();
if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
for(int i = 2; i< n; i++) {
if(Character.isLowerCase(word.charAt(i))) {
return false;
}
}
}else {
for(int i = 1; i<n;i ++) {
if(Character.isUpperCase(word.charAt(i))) {
return false;
}
}
}
return true;
}
/**
* Approach using LAMBDA 
* Time Complexity - O(N)
* @param args
*/
public boolean detectCapitalUse3(String word) {
if(word.length() <= 1) return true;
Predicate<Character> correctCase = Character::isLowerCase;
if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
correctCase = Character::isUpperCase;
}
for(int i = 1; i < word.length(); i++) {
if(!correctCase.test(word.charAt(i))) return false;
}
return true;
}