Unix Commands Interview Questions

1. How to list out the latest 3 modified files in unix? 
$> ls -t | head -3 
ls -t lists out all the files in the present directory in the order of modified date. Use head -3 with a pipe symbol to get the top 3 lines.


or


$> ls -lt | head -4 
ls -lt will list out all the files in the present directory in the order of modified date. Use head -4 to get the top 3 lines (including a header of the total). 


The most commonly used general syntax is : ls -t | head -<n> 
where n is the number of files you want to display. 


2. How to list out all the hidden files in Unix? 
Use the option -a  or -A . Hidden files in unix are normal files but are prefixed with '.' . 
Then, what is the difference between 'ls -a' and 'ls -A' ? 
'ls -a' will display all the hidden files including the current directory ('.') and the parent directory ('..'). 'ls -A' will not display current and parent directories. 


You can check the difference by taking the count also. 


$ ls -A | wc -c
     320
$ ls -a | wc -c
     325



3. How to display or print the first line of a file? 
$ head -1 filename 
To print first 'n' lines of a file : head -<n> filename 


4. How to display or print the last line of a file? 
$ tail -1 filename
To print last 'n' lines of a file : tail -<n> filename 


5. How to display nth line of a file?
You can do this by using the combination of head and tail commands. First, get the first 'n' lines and 'tail' the last line. 
$ head -<n> filename | tail -1


6. How to reverse a string in Unix? 
It is very easy to do in unix. Use the rev command. 


$> echo "unix program" | rev

margorp xinu

7. How to compress or zip a file in Unix? 
Use the inbuilt command [zip] to  do this. 
$> zip zippedfile filename
For multiple files : $> zip zippedfile filename1 filename2 filename3

8. How to unzip a file in Unix? 
Use the inbuilt command [unzip] to do this.

$ unzip -f zippedfile.zip 


9. How to test if a zip file is corrupted or not in Unix? 
Use the same unzip command but with -t switch. 
$> unzip -t zippedfile.zip
A sample output looks like this : 
$> unzip -t archivetest.zip
Archive:  archivetest.zip
    testing: testsample.txt           OK
No errors detected in compressed data of archivetest.zip.


10. How to check the type of a file in Unix? 
To know the type of a file use the [file] command as below :
$> file filename
Example : 
$> file abc.txt
abc.txt : ASCII text
To know the technical MIME type of the file, use the option '-i'. 
$> file -i abc.txt
abc.txt : text/plain; charset=us-ascii
or you may get the below output
abc.txt : regular file 


11. How to check if a file is zipped or not in Unix? 
We can use the [file] command as discussed earlier. If the file is zipped, the result will be as below: 
$> file -i filename.zip 
filename.zip : application/x-zip











0 comments:

Post a Comment