Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Showing posts with label Shell. Show all posts
Showing posts with label Shell. Show all posts

Saturday, 31 January 2015

Secure way of deleting files in Unix

January 31, 2015 Posted by Dinesh , , , , , ,

As I mentioned in the previous post there are simple techniques that can recover your deleted file (by using simple 'grep' or 'strings' utilities).
Even some data recovery tools does the same thing. So if you want to delete some data on the disk without being worried about the retrieval, then
you should probably over write the disk which has your file content.

shred utility available in Linux does the same thing.
shred actually overwrite the specified file repeatedly, in order to make it harder for even very expensive hardware probing to recover the data.
By default shred overwrites the file 25 times with the junk data.

you can chose to remove the file after over writing using -u (unlink)
There are multiple options with shred to explore.

$ shred -u filetobedeleted.txt

Just to see how it works, let say my script is writing some data to the file 'testlog.log' repeatedly after every 1 min.
I am tailing the file in one terminal. And in other terminal I did execute shred.
 
$ sh writetodisk.sh &
$ tail -f testlog.log
aaa
bbb
ccc
ddd


$ shred testlog.log

Now observe the terminal one

$ tail -f testlog.log
aaa
bbb
ccc
ddd
\{XÁÀà_ç æIƒòDÊ5žq­Æ 8<TÝõ ¬ S õŸt1’ïNÐ , éM‚?$Väé@. l"®ÎþÌÕæ ‡Ù+Ž’ bªO"× #f©ÎçN‰/h÷¡çÊhÇöŸz!*ÀA?RAo%æ} ÛZ½PSàpû7Íû3U_ ’e^u÷züê¾Ú6óš¶„Ë[Fœ;½êê±î÷]¤¥ˆi                                                                                  ÕÎ8ƒ:SÎq3®B h€'Q“ãªF¹X‘Q'†GÁ–oõ»hï eþ:½U4Úy_£È‘”f}"J_ŠÒ‡±Ê0íÕwº }rºŸoÇpÜ Wá‚À°xfeÒ?ÕC·         ‰JðhJë ™ÀQêM]ÞÑÅ,A {9b ÑùÇ@©}ÅŠ½°Ò¡øÜK-òõ ªLoLƒü
GýÑeÈ#WsG`Þ¼µÅ"–> T/~ [ºÝ ¸ýŒ<C8îzD±š¨š J
#Lwk{lû´köAٍ^0ê(9¿Ó Xnš¼¼ýc+7×Ãó ‡@ ;¥
                                        ŽBýˆÔ
                                              ÀF ⍠?’‰´q’+iQ‰ Y¸¯`± {·;²&%6ÈÄLYdù½­ š¼ÑÖi…ö±É* ÝÜ(Y2Ðc FÔ]þŠ ˜° ˜ƒTãðõ,l‚šl„bÜ8Å òU='µ YR™&iõqmôT ¤¿)“G[¡9îÎD ÉšDÒ–„xFÀjKNs„)½3̆^¹°w

you can see that the shred filled the contents of the file with garbage data.



How to recover a file that was removed using 'rm' command ?

January 31, 2015 Posted by Dinesh , , ,

In Unix like file systems, the system uses 'hard links' to point to piece of data that you write to the disk.
So when you create a file, you also create its first hard link. You can create multiple hard links using 'ln' command.
When you "delete" a file using rm command, normally you are only deleting the hard link.

If all hard links to a particular file are deleted, then the system removes only the reference to the data and indicate that the blocks as free. But it won't actually delete the file.

If your deleted file is opened by any running process then it means you still have one link left to your file !!.
check if any process who works on your file using lsof command

$ lsof | grep "myfile.txt"
COMMAND    PID     USER   FD      TYPE    DEVICE   SIZE     NODE    NAME
pgm-name   7099    root   25r    REG     254,0    349      16080   /tmp/myfile.txt

Using the process and file descriptor you can try copying the file


$ cp /proc/7099/fd/25 /mydir/restore.txt

If lsof didn't list your file then you could try to locate your data reading directly from the device.
But this works only if blocks containing your files haven't been claimed for something else.

To make sure no one else over writes that free blocks, immediately remount the file system with read-only and then search for your file.

$ mount -o ro,remount /dev/sda1
$ grep -a -C100 "unique string" /dev/sda1 > file.txt

Replace /dev/sda1 with the device that the file was on and replace 'string' with the unique string in your file.
This does is it searches for the string on the device and then returns 100 lines of context and puts it in file.txt.
If you need more lines returned just adjust -C options as appropriate. Alternatively you can use -A, -B options with grep to print lines before and after the matched string.

You might get a bunch of extra garbage date, mostly some binary data but you can get your data back.
If you don't want this binary data then you can apply 'string' on the device and grep for the unique string

$ strings /dev/sda1 | grep -C100 "unique string" > file.txt



Monday, 24 November 2014

Change the screen brightness using bash script - xrandr

November 24, 2014 Posted by Dinesh , , ,

In my Ubuntu 14.0 (Dell Inspiron), brightness controls were not working at all. So I started searching for other alternatives to sets the brightness.

finally I found this xrandr.
it is great tool to set the brightness and even to rotate the screen.


--brightness flag can be used to set the brightness (best values: 0 - 1)
--brightness flag cab be used to rotate the screen (possible options : normal, left, right) 

Usage:
          ./brightness_control.sh +      # Increase the brightness by 0.05
          ./brightness_control.sh  -       # Decrease the brightness by 0.05
          ./brightness_control.sh 1       # Set brightness to 1
 
 



Monday, 18 November 2013

Unix command line tricks

November 18, 2013 Posted by Dinesh , ,
1. Ever tried creating pdf files in your unix machine ??

man -t ascii | ps2pds - > ascii_man_page.pdf

-t flag formats the output and ps2pds converts post script to pdf.
hyphen (-) after ps2pdf command indicates it to read input from stdin and write output to stdout.


2. Want to terminate the script after first failure ?

'set -e' thats it. it does everything.

$> cat setexit.sh

#/bin/bash
set -e
echo "line 1"
cat tmp.x.12.12
echo "line 2"


$> ./setexit.sh
line 1
cat: tmp.x.12.12: No such file or directory #line 2 is not echoed


3. Simple way to create huge file

yes, we have 'yes' in unix to do that. yes will echo what ever you give as argument.

#press ctr+c after a while
$yes "some random text..." > bigfile.txt

'yes' has another interesting advantage. just imagine to answer yes to the every question by bash.

$rm file.txt
rm: remove regular file 'file.txt' ?

#you probably give 'y' to remove it. what if you want to remove 100 such files?

yes | rm *.sh
  

though this can be achieved just by ignoring alias ( \rm *.sh ) this is just an example to demonstrate the usage.


4. Creating dirty random number

we have $RANDOM shell variable to generate a random number may be max of 5 characters. If you wish to create a big random number use 'mcookie'. This command generates a "magic cookie," a 128-bit pseudorandom hexadecimal number, normally used as an authorization signature by the X server. This also available for use in a script as a quick and dirty random number.

$mcookie
a2cae14a060720bca183d05f165a5a8e


5. Get directory name or file name from path and file extension

#extract dir name and file name
$> basename /dir1/dir2/file.txt      
file.txt  
$> dirname  /dir1/dir2/file.txt 
/dir1/dir2

#Extract extension 
$> path="/dir1/dir2/file.txt"
$> ext=${path##*.}
$> echo $ext
txt


6. Simple 'cut'

var="one two three"
set -- $var
a=${1};   #one 
b=${2};   #two
c=${3};   #three

Just a basic example to avoid invoking forked process (cut/awk)


7. Base conversion

'bc' can convert from any base to any.

Ex: decimal to hexadecimal conversion
echo 'obase=16; ibase=10; 64' | bc            # (ibase=input base, obase=output base)

This will convert 64 from base 10 to base 16.



Friday, 1 November 2013

Programmable Completion : Autocomplete the arguments of your program

November 01, 2013 Posted by Dinesh ,
Auto completion is one of the best features in bash. How good if it completes argument for your program as well !!

The Bash complete and compgen builtins make it possible for tab completion to recognize partial parameters and options to commands. In a very simple case, we can use complete from the command-line to specify a short list of acceptable parameters.

with complete [option] [command] you define the completion for some command.

A basic example to illustrate auto completion:

lets think we have a script called 'run.sh' which will take 4 arguments --all, --help, --html, --version.
as you type run.sh -[TAB] it should display all the above four option.
to make it work lets write a small function will will be loaded by complete when ever TAB is pressed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# file: load_opt
_load_opt ()   
{                
  local cur
  COMPREPLY=()   
  cur=${COMP_WORDS[COMP_CWORD]}

  if [[ ${cur} == -* ]]
  then
    COMPREPLY=($(compgen -W "--all --help --html --version" -- $cur))
  return 0
  fi
}

complete -F _load_opt run.sh

save the file as load_opt.  and source it before running run.sh. then it shows the magic.

$  source load_opt

$  run.sh -[TAB][TAB]
--all --help --html --version

$ run.sh --h[TAB][TAB]
--help --html


How it works ?

Once the load_opt script is sourced, bash understands that run.sh arguments will be completed bye load_opt function which is specified by complete command at the end of load_opt file.
so when ever TAB is pressed  _load_opt function will be called.
This script has some special shell variables.

COMP_WORDS
An array variable consisting of the individual words in the current command line.
COMP_CWORD
An index into ${COMP_WORDS} of the word containing the current cursor position.
COMPREPLY
An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility
a local 'cur' variable is used to point current completion word.

so if your option starts with - it will match -* and set the value of COMPREPLY to the output of compgen [ check here ] command. compgen will return the matching words of 'cur'
and those set of words are assigned to COMPLREPLY array.
bash will now print those word to console.


But it is not a good idea of sourcing the loader before running the script.
so create this load_opt file under /etc/bash_completion.d/ directory. all the scripts which are under  /etc/bash_completion.d/ will be loaded by bash in the start up.
After adding the file under that directory you can run bash then run the script or you can source that file alone and run the script.


Note:
above example work if you run your script run.sh[TAB] not ./run.sh[TAB]. if you want it to work with ./ as well add 'complete -F _load_opt ./run.sh' also at the end of load_opt file.




compgen - List All Unix Commands !!

November 01, 2013 Posted by Dinesh , No comments

compgen is bash built-in command and it will show all available commands, aliases, and functions.
and it is used to get the specific set of words from a word list ( ?? )

To list all the commands available :

$ compgen -c
alert
c
d
egrep
fgrep
..
..
..
bzexe
espdiff
sol
gnome-mines
gnome-sudoku


To list all the bash shell aliases available :

$ compgen -a
alert
c
d
egrep
fgrep
grep
l
la


To list all the bash build-ins :

$ compgen -b
.
:
[
alias
bg
bind
break
builtin
caller
cd


To list all the bash keywords :

$ compgen -k
if
then
else
elif
fi
case
esac
for
select
while
until
do
done
in
function
time
{
}
!
[[
]]
coproc


To list all the bash functions :

dinesh@ubuntu:~$ compgen -A function
__colormgrcomp
__expand_tilde_by_ref
__get_cword_at_cursor_by_ref
__grub_dir
__grub_get_last_option
..
..
_zeitgeist_daemon
command_not_found_handle
dequote
quote
quote_readline

-A (action) is very useful option. The action may be one of the following to generate list of possible completions.
alias, arrayvar, binding, builtin, command, directory, enabled, disabled, export, file, function, group, hostname, job, keyword, running, service, setopt, signal, user, variable.


To get word[s] from word-list :


dinesh@ubuntu:$ compgen -W "aa ab ac ba bb"
aa
ab
ac
ba
bb
dinesh@ubuntu:$ compgen -W "aa ab ac ba bb" -- b
ba
bb
is it really useful ??

Friday, 11 October 2013

Difference between array[@] and array[*] in shell

October 11, 2013 Posted by Dinesh , , No comments
It is important for quoting and spacing that the ${array[@]}
format (rather than ${array[*]}) is used, and also that double quotes are put around the whole construct. 



items=(pen "permanent marker" pencil "temporary marker")
 
for item in ${items[@]}
do
  echo "Item is : $item"
done

Item is : pen
Item is : permanent
Item is : marker
Item is : pencil
Item is : temporary
Item is : marker


for item in ${items[*]}
do
  echo "Item is : $item"
done

Item is : pen
Item is : permanent
Item is : marker
Item is : pencil
Item is : temporary
Item is : marker



items[@] and items[*] produced the same output and which is not expected. "permanent" and "marker" are treated as two different words in both the cases though it is a single word. lets try now with the quotes around the array..

items=(pen "permanent marker" pencil "temporary marker")
for item in "${items[@]}"
do
  echo "Item is : $item"
done

Item is : pen
Item is : permanent marker
Item is : pencil
Item is : temporary marker
 

 YES this what we expected.... but items[*] will not behave this way.


for item in "${items[*]}"
do
  echo "Item is : $item"
done

Item is : pen permanent marker pencil temporary marker


the * is not suitable either with or without quotes. Without quotes, it does the same as the @ symbol. With quotes, the whole array is boiled down into a single string.



Monday, 1 April 2013

Shell Special variables and TEST flags

April 01, 2013 Posted by Dinesh , No comments


Here are some shell special variables:


Special Shell Variables:

VariableMeaning
$0Filename of script
$1Positional parameter #1
$2 - $9Positional parameters #2 - #9
${10}Positional parameter #10
$#Number of positional parameters
"$*"All the positional parameters (as a single word) *
"$@"All the positional parameters (as separate strings)
${#*}Number of positional parameters
${#@}Number of positional parameters
$?Return value
$$Process ID (PID) of script
$-Flags passed to script (using set)
$_Last argument of previous command
$!Process ID (PID) of last job run in background





TEST Operators: Files


OperatorTests Whether-----OperatorTests Whether
-eFile exists-sFile is not zero size
-fFile is a regular file
-dFile is a directory-rFile has read permission
-hFile is a symbolic link-wFile has write permission
-LFile is a symbolic link-xFile has execute permission
-bFile is a block device
-cFile is a character device-gsgid flag set
-pFile is a pipe-usuid flag set
-SFile is a socket-k"sticky bit" set
-tFile is associated with a terminal
-NFile modified since it was last readF1 -nt F2File F1 is newer than F2 *
-OYou own the fileF1 -ot F2File F1 is older than F2 *
-GGroup id of file same as yoursF1 -ef F2Files F1 and F2 are hard links to the same file *
!NOT (inverts sense of above tests)
* Binary operator (requires two operands).


Parameters/String Operations on shell (Bash) without using any third party tools

April 01, 2013 Posted by Dinesh , No comments


Parameter Substitution and Expansion:

ExpressionMeaning
${var}Value of var (same as $var)
${var-DEFAULT}If var not set, evaluate expression as $DEFAULT *
${var:-DEFAULT}If var not set or is empty, evaluate expression as $DEFAULT *
${var=DEFAULT}If var not set, evaluate expression as $DEFAULT * (value is assigned to var)
${var:=DEFAULT}If var not set, or is empty, evaluate expression as $DEFAULT * (value is assigned to var)
${var+OTHER}If var set, evaluate expression as $OTHER, otherwise as null string
${var:+OTHER}If var set, evaluate expression as $OTHER, otherwise as null string
${var?ERR_MSG}If var not set, print $ERR_MSG and abort script with an exit status of 1.*
${var:?ERR_MSG}If var not set, or is empty, print $ERR_MSG and abort script with an exit status of 1.*
${!varprefix*}Matches all previously declared variables beginning with varprefix
${!varprefix@}Matches all previously declared variables beginning with varprefix



* If var is set, evaluate the expression as $var with no side-effects.

String Operations:


ExpressionMeaning
${#string}Length of $string
${string:position}Extract substring from $string at $position
${string:position:length}Extract $length characters substring from $string at $position [zero-indexed, first character is at position 0]
${string#substring}Strip shortest match of $substring from front of $string
${string##substring}Strip longest match of $substring from front of $string
${string%substring}Strip shortest match of $substring from back of $string
${string%%substring}Strip longest match of $substring from back of $string
${string/substring/replacement}Replace first match of $substring with $replacement
${string//substring/replacement}Replace all matches of $substring with $replacement
${string/#substring/replacement}If $substring matches front end of $string, substitute $replacement for $substring
${string/%substring/replacement}If $substring matches back end of $string, substitute $replacement for $substring
expr match "$string" '$substring'Length of matching $substring* at beginning of $string
expr "$string" : '$substring'Length of matching $substring* at beginning of $string
expr index "$string" $substringNumerical position in $string of first character in $substring* that matches [0 if no match, first character counts as position 1]
expr substr $string $position $lengthExtract $length characters from $string starting at $position [0 if no match, first character counts as position 1]
expr match "$string" '\($substring\)'Extract $substring*, searching from beginning of $string
expr "$string" : '\($substring\)'Extract $substring* , searching from beginning of $string
expr match "$string" '.*\($substring\)'Extract $substring*, searching from end of $string
expr "$string" : '.*\($substring\)'Extract $substring*, searching from end of $string


* Where $substring is a Regular Expression.

Refer http://itsjustsosimple.blogspot.in/2013/02/all-about-variablesparameters-in-shell.htmlfor few examples.



Sunday, 3 February 2013

All about variables/parameters in shell

February 03, 2013 Posted by Dinesh , , No comments


Stripping Variable Strings By length:


Syntax: ${parameter:starting_index:number_of_chars}

${variable:3}      # foobar becomes bar
${variable:3:2}   # foobar becomes ba
${variable: -4}   # foobar becomes obar


Upper and lower case :


y="this IS small"
echo "${y^^}"
THIS IS SMALL

y="THIS is BIG"
echo "${y,,}"
 this is big

Removing a Part:


name=${var#removepat}
This will remove 'removepatt' from variable(begining) var and assign to name

name=${var%removepat}
can use % to remove the pattern at the end. useful when one wish to remove trailing / from path names

##   Deletes longest match of $removepat from front of $var.
%%  Deletes longest match of $removepat from back of $var.


Here is the example which will tokenize positional parameters based on =

tmp=${1}
parameter=${tmp%%=*}     # Extract name.
value=${tmp##*=}               # Extract value.

if $1 is a=1, then
parameter=a     #strip from back till = ; so =* will be removed    
value=1            # strip from front till = ; so *= will be removed

Substring Replacement:


${string/substring/replacement}
Replace first match of $substring with $replacement.${string//substring/replacement}Replace all matches of $substring with $replacement.
string=abcABC123ABCabc
echo ${string/abc/xyz}                  # xyzABC123ABCabc
echo ${string//abc/xyz}                 # xyzABC123ABCxyz

Following will simply delete the pattern from string.
string=abcABC123ABCabc
echo ${string/abc/}            # ABC123ABCabc
echo ${string//abc/}           # ABC123ABC


Get Length:

To calculate length of any variable in shell, # can be used.

a="ABCD"
${#a}
4

Calculate number of elements in array:

$ os=("linux" "solaris" "aix")
$ echo {#os[*]}
3
$ echo {#os[@]}
3

@ or * can be used to access all elaments of an array.
These native methods will be faster since we are not invoking any third party tools.

Note: without '(  )' result can't be treated as array.

AWK/CUT implementation (simplified) :


dinesh@ubuntu:~$ a="abc 123 qqq"
dinesh@ubuntu:~$ set -- $a
dinesh@ubuntu:~$ echo $1
abc
dinesh@ubuntu:~$ echo $2
123
dinesh@ubuntu:~$ echo $3
qqq
dinesh@ubuntu:~$

Thursday, 10 January 2013

Extract particular lines from a file using 'sed'

January 10, 2013 Posted by Dinesh , , No comments


1. Extract Using Line Numbers :

1
2
3
sed -n '10'p <filename>                 #Prints  10th line of file
sed -n '10,20'p <filename>            #Print lines 10 to 20
sed -n '10,$'p <filename>              #Print lines 10 to end

$ sed -n '10'p file is equivalent to  
$ sed '10!d' file and results
Line 10

The default output behavior is to print every line of the input file stream.The explicit 10p command just tells it to print the tenth line
So in the first example since sed is called with -n flag, it suppress the default output and prints 10th line
in the  second example, (note -n is not used) sed will delete (d) the line if it is not (!) line number 10

Similarly printing lines from 2 to 4 :

1
2
sed -n '2,4'p file
sed '2,4!d'  file

Line 2
Line 3
Line 4


2. Extract Using Pattern :

Some time we may need to print the lines which matches the pattern. that also can be done using sed

1
sed -n '/main/p' check.cpp

will print the lines which matches the pattern main in check.cpp file.
grep can be used as an alternative

similarly instead of 'p' (print), 'd' (delete) can be used to delete the line matching the pattern from the file.

1
sed '/main/d' check.cpp > newfile.cpp


3. Extract non empty lines :

Following will remove the empty lines from the file. and redirect remaining to new file.

1
2
sed '/./!d' check.cpp > newfile.cpp
sed '/^$/d' check.cpp > newfile.cpp





Saturday, 5 January 2013

Useful aliases in Shell

January 05, 2013 Posted by Dinesh , , No comments

Like 'ddd' , we can see the code while debugging with gdb too ... 
Set the '-tui' flag for gdb to enable this feature. and '-quiet' will suppress copyright messages. 
      
  alias gdb='gdb -tui -quiet'





Read as many as possible without scrolling

alias tail='tail -n $((${LINES}-2))'

Reading hex data
what most people want from od
alias od='od -Ad -tx1 -v'
Create a directory and go into it
md () { mkdir -p "$1" && cd "$1"; }


Write these functions in bashrc file,common in other languages, available in the shell
ord() { printf "0x%x\n" "'$1"; }
chr() { printf $(printf '\\%03o\\n' "$1"); }

Ex Usage:
dinesh@ubuntu:~$ chr 65
A
dinesh@ubuntu:~$ ord a
0x61
dinesh@ubuntu:~$ ord 1
0x31
dinesh@ubuntu:~$ 


Thursday, 4 October 2012

Timeout - timed wait in shell scripting

October 04, 2012 Posted by Dinesh , , No comments
TMOUT is the shell built in variable to set the timeout .

TMOUT is used in three different ways: by the read builtin command, by the select builtin, and by the interactive bash shell. If it is unset, or equal to zero, then it is ignored. If it has any positive value, then these three commands which make use of it will timeout after $TMOUT seconds.

Example:
$> cat timeout.sh


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash

TMOUT=5
read -p "Enter password : " pass
if [ $? -eq 0 ]
then
   echo "Password is $pass"
  else
    echo "Timed out...."
fi



same effect can be achieved using read with -t option.
read -t 5 -p "Enter password : " pass


PIPESTATUS and its Alternative

October 04, 2012 Posted by Dinesh , , No comments
$> cat /etc/hosts | grep 000.000
$> $?
1


$> cat /etc/hosts | grep 000.000 | uniq
$> $?
0

Why is it returning success (0) though it fails during grep ??
the return code of a pipeline will be that of the return status of the rightmost command .
How to resolve this ??
use inbuilt PIPESTATUS variable.

PIPESTATUS is a array variable which contain the exit status of each command in piped commands. 

$> cat /etc/hosts | grep 000.000 | uniq
$> echo ${PIPESTATUS[*]}
0 1 0

here $PIPESTATUS[0] contains the exit status of cat /etc/hosts command
$PIPESTATUS[1] contains the exit status of grep 000.000
$PIPESTATUS[2] contains the exit status of uniq


The other way around for this is setting pipefail.

$> set -o pipefail
$> cat /etc/hosts | grep 000.000 | uniq
$> $?
1


Saturday, 18 August 2012

Auto Correct Directory Names / Shell Options

August 18, 2012 Posted by Dinesh , , No comments

"shopt" can be used to correct typos in cd command.
you can use "cdspell" which will auto correct the directory name you have entered.

Usage:   shopt -s cdspell  
( -s : set
 -u : unset)

$ cd /usr/local/sben     will results in bash: cd: /usr/local/sbEN: No such file or directory
but once you have enabled cdspell option,

$ cd /usr/local/sben    
/usr/local/sbin
$pwd
 /usr/local/sbin

some other useful options are,
histappend : this will append to the history file, instead of overwriting it
checkwinsize: check the window size after each command and, if necessary, update the values of LINES and COLUMNS.

lot of other options are available with shopt.
to list all these options used shopt -p

Or you can refer the man page  http://ss64.com/bash/shopt.html





Monday, 4 June 2012

`Tar`- An Ultimate Archive Utility

June 04, 2012 Posted by Dinesh , , No comments
How to use tar
tar  [options] [name of tar file to be created] [list of files and directories to be included]

1. Creating an archive using tar
    
      $ tar -cvf target.tar file1 file2 dir1 
      $ tar -cvzf target.tar.gz dirname/             [ creates gzipped tar archive file ]
      $ tar -cvjf target.tar.bz2 dirname/           [ creates bzipped tar archive file ]

    Note: this -cvf options alone does not provide any compressions

2 Extracting an archive
 
      $ tar -xvf target.tar
      $ tar -xvzf target.tar.gz                            [ extracts gzipped tar archive file ]
      $ tar -xvjf target.tar.bz2                          [ extracts bzipped tar archive file ]

3. Listing an archive

      $ tar -tvf target.tar
      $ tar -tvzf target.tar.gz                             [ lists gzipped tar archive file ]
      $ tar -tvjf target.tar.bz2                           [ lists bzipped tar archive file ]

4. Extract a file/directory

    $ tar -xvf target.tar /mydir/myfile
    $ tar -xvzf target.tar.gz /mydir/myfile
    $ tar -xvjf target.tar.bz2 /mydir/myfile 

    if you want to extract a group of files from the archive use -wildcard option
    $ tar -xvf target.tar --wildcards '*.cc'
 
5. Adding a file or directory to an existing archive
 
    You can add additional files to an existing tar archive by specifying -u or -r options.
    use -u option if u do not want duplicates in the tar archived file. -r option will add the file to the existed archive if it exist also.

    $ tar -rvf target.tar newfile     or $ tar -uvf target.tar newfile

    Note: this can't be done for gz or bz2 archives.
 





'cat' can be harmful..

June 04, 2012 Posted by Dinesh , , No comments
'cat' can be harmful at times. some people might have lost the data because of improper usage of cat command like cat > filename.txt, or it can do over write some existing files data without prompting the user.
to get rid out of these situations
1. open the terminal
2. execute " set -o noclobber "
that's it. now next time when cat tries to over write the existing file it will prompt the user.