Showing posts with label ubuntu tutorial. Show all posts
Showing posts with label ubuntu tutorial. Show all posts

Thursday, April 2, 2015

Renaming and Moving files ,directories in ubuntu

 
 """
Moving/Renaming Files and Directories


Commands

mv       Move or rename files & Directories.

mv source destination

mv -i source destination



To get better understanding.
Create two files and two directories on your Desktop.

files --file1 file2

directories -- blog-promotion backup 

File Renaming

cam@hack3r:~/Desktop$ mv file1 file2

It renamed file1 --> file2 but there's file with same name so it is deleted.


A File moving into a Directory.

cam@hack3r:~/Desktop$ mv file2 backup

This command moves file2 into backup Directory.


A Directory being moved into a Directory

cam@hack3r:~/Desktop$ mv backup blog-promotion

This moves backup folder into blog-promotion.Since both are in Desktop directory we ddn't specify any path.

"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Copying files and directories in ubuntu

"""
Copying Files and Directories


Commands


cp file1 file2             Copy contents of file1 to file2   

cp file1 file2 file3 dir1  Copy file1,file2,file3 to dir1

cp -r dir1 dir2            copy dir1 contents to dir2.

You can use cp -i file1 file2 for interactive mode.
For copying directories cp -r is a must.

Explaining Screenshot.

cd Desktop

Changes my directory to Desktop.

nano file1

creates a file called file1.You enter some info.Once you are done press (ctrl+o) followed by hitting enter and lastly
ctrl+x to exit

To create a file named file1
[nano file1 --> fill some info --> ctrl+0 -->hit enter-->ctrl+x ]

cat file1

It displays the contents of file1

cp file1 file2

It creates a new file called file2 in the same directory with the contents of file1.

[* Here we didn't give any path,we just gave two file names.what if we want to copy file1 to another directory.
In that case use full paths. 
cp source-file destinatio-file
cp /home/cam/Desktop/file1 /home/cam/file2 
The above command copies file1 which is on my Desktop to my cam diectory which is in home ]


mkdir blog-promotion

It creates a new directory called blog-promotion on my Desktop.

cp file1 file2 blog-promotion

copies both file1 and file2 to a folder or directory called blog-promotion.

ls blog-promotion

shows all files and directories inside blog-promotion.

cd .. 

Takes me to previous directory.

skipping to end.


cp -i 

Before replacing a file which already exists it will ask you...that's called interactive


"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Removing Files and directories in ubuntu

"""
Removing Files


Commands


rm file    Removes a file

rm -r dir    Removes a dir(directory) and 
     all files in it.

rm -f file    Force removal.




* nano filename (opens a file or creates if there is no such file)
In this post we have created two files in target directory
1.this-week-target
2.blog-taarget (Spelling mistake bare with me)
"""

"""

Explaining the screenshot (screenshot @ bottom)

As I opened my terminal I'm at my home directory.

cd Desktop 

changed my directory to Desktop(it's D )

mkdir target

It creates a new directory called target

cd target

It changes my current directory to target.So now i'm in the target directory.

nano this-week-target

It creates a file called this-week-target in target folder.

So you need to type some info.Now to save the file you need to press (ctrl+o) and hit enter.
Now press ctrl+x to get back to normal terminal.

To create a file [nano filename --> fill the file with some info --> ctrl+o --> hit enter--->ctrl+x]
nano blog-taarget creates another file

now ls command shows there are two files in target directory.

cat blog-taarget 

The above command shows the content of the file..

rm blog-taarget removes the file

now you can give ls and see there is only one file in target directory.

Now I want to remove the target directory also.Since target directory is on Desktop,I'll change my directory to Desktop.

cd .. (cd followed by two dots)

The above command takes me to the previous directory.

Now to remove the target directory and all files inside it we use

rm -r target

rm -r means remove recursively...
So be careful while using rm -r.
now ls on Desktop you will not see the target directory.




"""

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Saturday, March 28, 2015

Environmental variable in ubutnu mycat implementation


"""

.   This directory or current directory

..   The parent directory

cd -        Change to previous directory

Usage: cd .
cd ..
There's output from my computer at the end of this post.

To display last working directory

echo $OLDPWD

Demo:

cam@hack3r:~$ pwd
/home/cam
cam@hack3r:~$ cd /var/tmp
cam@hack3r:/var/tmp$ pwd
/var/tmp
cam@hack3r:/var/tmp$ echo $OLDPWD
/home/cam
cam@hack3r:/var/tmp$ cd -
/home/cam
cam@hack3r:~$ pwd
/home/cam
cam@hack3r:~$ 


How to implement your version of cat

question:why do i need to implement another cat version?
Ans: If you install java jdk or django..you would know.
If you don't add into environmental path,then you can't run that program from other directories


cam@hack3r:~$ which cat
/bin/cat
cam@hack3r:~$ 

That executable is at /bin/cat
Click on computer browse through bin folder and you'll find cat(a diamond shaped file)
copy and paste it on Desktop;now rename it to mycat
================================================================================================

cam@hack3r:~/Desktop$ ls
1  1~  2  2~  D  msf_install.sh~  mycat  trytac.txt  Untitled Document~



cam@hack3r:~/Desktop$ mycat 1
No command 'mycat' found, did you mean:
 Command 'mmcat' from package 'sleuthkit' (universe)
 Command 'mlcat' from package 'svtools' (multiverse)
 Command 'mscat' from package 'libpwiz-tools' (universe)
 Command 'mcat' from package 'mtools' (main)
mycat: command not found


cam@hack3r:~/Desktop$ ./mycat 1
hi i'm in 1
i'm last line
cam@hack3r:~/Desktop$ 


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



cam@hack3r:~$ pwd
/home/cam
cam@hack3r:~$ cd /
cam@hack3r:/$ pwd
/
cam@hack3r:/$ cd /home/cam/Desktop/D
cam@hack3r:~/Desktop/D$ pwd
/home/cam/Desktop/D
cam@hack3r:~/Desktop/D$ cd .
cam@hack3r:~/Desktop/D$ cd ..
cam@hack3r:~/Desktop$ 

"""




Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

MAN Command in ubuntu explained

"""
man command revisited

man ls 

it displays huge output...
You need to hit enter to move down...but it does move only 1 line...
you use space,it displays page by page rather line by line.
use g to goto top of the page
use [shift+g] to move to down of the page.
q to quit

Environmental Variables == Storage location that has name and value.


==>Mostly uppercase names


PATH is one of the environmental variables.

echo $PATH (we have to use $ sign before the variable)

Output

cam@hack3r:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/cam/bin:/usr/local/java/jdk1.8.0_40/bin


This will not be same for you;

they are different paths separated by ':'

Long back I've installed oracle java jdk and added to environmental variables.It's showing the path of jdk.

Question:
Why are there so many paths??

If you type a command then it is first searched in all the paths starting from /usr/local/sbin (this is for my laptop).
If the command typed by you is not in the path then it will display command not found.

which command 

You might want to know in "which" path does ls reside.you can find that by using wich command

which ls

cam@hack3r:~$ which ls
/bin/ls
cam@hack3r:~$ which man
/usr/bin/man

Note: Which doesn't work for builtins;so don't try it on cd












"""







Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

what exactly is a Shell in ubuntu or Linux

 """
shell ==>
1.The default interface to linux
2. The program that accepts your commands and execute those commands
3. Also called commandline interpreter

To acess it on ubuntu desktop/laptop(ctrl+alt+t)
when shell(Terminal emulator application) is opened it shows you prompt.Prompt waits for you to type something in it.
(type whoami)


question: Why use a CLI when we have graphical interdace?
If you want to acess some linux server ,most server distributions doesn't include GUI.
There will be many tedious tasks like renaming a 1000 files....
So in GUI you have to right click and rename,but if you get familiar with commandline you can do it with a command..


Normal VS root

A prompt  will typically look like
[username@computername ~]$
But if you want to have more privelages then you need to change to root prompt.
[root@computername:~]#
To change to root prompt you have to type
An Example from my laptop

cam@hack3r:~$ sudo su
[sudo] password for cam:
root@hack3r:/home/cam#

Observe there is a different symbol for root at the end(#)

Question:
Now in the last post we've discussed a root (directory),mother of all directories.Is that root is same is this root prompt??
No..That is a directory.This root is an account,like super account.

Root,The Superman account
It's like Administrator account in windows.
I've an account called cam on my laptop..
cam<root
for that matter any account on my ubuntu have less privelages than root.


Question:
Why is there a root account when i can access it with a simple command.why can't my user account have all privelages?
Answer:
Simple,In most linux servers there will be multiple user with different tasks...
Only system admins have access to root.You might have seen in many movies people trying to access root.


Tilde(~) Expansion

wait i've seen this somewhere??
Yes it's on your prompt and it is called Tilde

~cam = /home/cam
~root=/root
~ftp = /srv/ftp

Try out these:

cam@hack3r:~$ sudo su
[sudo] password for cam:
root@hack3r:/home/cam# pwd
/home/cam
root@hack3r:/home/cam# cd ~
root@hack3r:~# pwd
/root
root@hack3r:~# cd ~cam
root@hack3r:/home/cam# pwd
/home/cam
root@hack3r:/home/cam# exit
exit
cam@hack3r:~$



Take out from this post



===========                        ==========
command                          Action
===========                        ==========

1.pwd                             displays present working directory

2.cd                             Change directory[you cannot type any directory.You've type the exact path]

3.sudo su                         To access root account from terminal

4.exit                             To exit from root account to normal account(Use root account carefully..)

5.Clear                            Clears the terminal application















 
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Basic Ubuntu/linux Commands


"""
Linux commands are case sensitive(capital letters are different from small letters)

==============        ==============
   Command            Action
 =============        ==============

 1. ls           lists directories and files

 2. cd           changes current directory

 3. cat          concatenates(add) and displays files

 4. echo          Displays arguments to the screen(print)

 5. man          Displays the manual.




 Ex 1:

 ls name_of_the_directory  
 note:if you have spaces in the name of your folder,you've to use "folder name"

 Ex:2

 ls "name of the directory with spaces"
 Shows all the files and directories inside the directory on which ls is performed


Ex:3

cd directory 

this can be bit confusing at first.Every directory is in some hierarchy.you cannot jump from one path to other..
Check the screenshot.

use pwd to know where you are.
Your prompt will start at /home/username
On my Desktop you can see there is only one directory D.
Inside D there are many directories.
To access my directories in D i've to use this commands.
cd Desktop/java
but for you to access usr directory which is in root directory you have to use this

cd /usr


Ex:4

echo My name is Ajay

Displays the line on terminal

echo $PATH 

Output

/usr/local/sbin:/usr/local/bin:


This may vary from user to user


Ex:

man cd 

man man (funny)

displays the documentation page of cd

well i know command cd so i can type man cd.what if i don't know which command to search for but i know just a word.
I want to edit a file.so i'll search a term edit rather a command.

doing vague search on man

man -k search_term



Output:

cam@hack3r:~/Desktop$ man -k edit
atobm (1)            - bitmap editor and converter utilities for the X Window...
bitmap (1)           - bitmap editor and converter utilities for the X Window...
bmtoa (1)            - bitmap editor and converter utilities for the X Window...
dconf-editor (1)     - Graphical editor for dconf
desktop-file-edit (1) - Installation and edition of desktop files
desktop-file-install (1) - Installation and edition of desktop files
djvused (1)          - Multi-purpose DjVu document editor.
ed (1)               - line-oriented text editor
..........      ....................
........     ...................
..........      ...................
Many more editors displayed


*** Extra
There is a command called tac reverse of cat command.
Can you guess what it does??
cat displays contents of file,so tac should display contents of file in reverse order[last line first;first line last].

nano is a tex editor that can be accessed from terminal by typing nano

cam@hack3r:~/Desktop$ nano trytac.txt     ==>check how to use nano
cam@hack3r:~/Desktop$ tac trytac.text      |
             |
i'm in last lines                          |
i'm in 2                                   |
i'm in 1                                   |
cam@hack3r:~/Desktop$                      |
                                           |
how to write and save in nano:    <=========

nano filename
A text editor will open in terminal don't panic.
type some lines hit enter...
now to save (ctrl+o) but now the cursor blinks after trytac.txt press enter.
Now you need to press (ctrl+x) to exit out of the editor







"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Directories structure in Ubuntu/Linux

Check Images Some images are taken from Linuxtrainingacademy.com video tutorials


"""
 /   "Root",the top of the file system

 /bin  Binaries and other executable programs

 /etc  System Configuration files

 /home      Home directories,if you have multiple users then you have different directories for different people


 /opt   Optional or third pirty software
 Ex:The editor i'm using is sublime text 3,which donot come bundled with ubuntu,so some of the third party
 softwares gets installed at /opt

 /tmp  Temporary space,typically cleared on reboot

 /usr   User related programs

 There will be sub directories inside these directories

 /var  Variable data like log files



Other directories

/boot  Files need to boot the operating system

/cdrom  Mount point for CD-ROMS


/dev  Device files,typically controled by the operating system and sys admins

/media  Mount removable devices

/mnt(used to mount external file systems),/proc(provides info about running process),/srv(contains data which is served by the system)




What to do with the info??

Just check these directories with ls -al command,see what files are in there...

just get an idea,don't panic....

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

The content below is optional.... You need not get into details
=================================================================================================

Application Data Structure

If you are from windows you would know all softwares would install @ 
C:\\Program files\software
or 
C:\\Program Files(x86)\software ==> For a 32 bit
C:\\Program Files (x64)==> for a 64 bit
or 
at custom location

Similarly 

Some external softwares in ubuntu get installed at

1. /usr/local/software

Inside the software you will have other directories (bin,etc,lib,log)

some install at

2. /opt/software

Inside the software you will have other directories (bin,etc,lib,log)



3. Google products get installed at
/opt/google
/opt/google/chrome
/opt/google/earth


There are bunch of other ways that programs get installed



"""
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Wednesday, July 10, 2013

What is bash??what the heck is shell??[Learn ubuntu/Linux with me -Day 3]

People often confuse with these terms.Some say Bash Commands,some say shell commands.It's really confusing.The below text is from this website.

What is Bash?

Bash is the shell, or command language interpreter, for the GNU operating system. The name is an acronym for the ‘Bourne-Again SHell’, a pun on Stephen Bourne, the author of the direct ancestor of the current Unix shell sh, which appeared in the Seventh Edition Bell Labs Research version of Unix.
Bash is largely compatible with sh and incorporates useful features from the Korn shell ksh and the C shell csh. It is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1). It offers functional improvements over sh for both interactive and programming use.
While the GNU operating system provides other shells, including a version of csh, Bash is the default shell. Like other GNU software, Bash is quite portable. It currently runs on nearly every version of Unix and a few other operating systems - independently-supported ports exist for MS-DOS, OS/2, and Windows platforms.

What is a shell?

At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.
A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.
Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.
A shell allows execution of GNU commands, both synchronously and asynchronously. The shell waits for synchronous commands to complete before accepting more input; asynchronous commands continue to execute in parallel with the shell while it reads and executes additional commands. The redirection constructs permit fine-grained control of the input and output of those commands. Moreover, the shell allows control over the contents of commands’ environments.
Shells also provide a small set of built-in commands (builtins) implementing functionality impossible or inconvenient to obtain via separate utilities. For example, cd, break, continue, and exec) cannot be implemented outside of the shell because they directly manipulate the shell itself. The history, getopts, kill, or pwd builtins, among others, could be implemented in separate utilities, but they are more convenient to use as builtin commands. All of the shell builtins are described in subsequent sections.
While executing commands is essential, most of the power (and complexity) of shells is due to their embedded programming languages. Like any high-level language, the shell provides variables, flow control constructs, quoting, and functions.
Shells offer features geared specifically for interactive use rather than to augment the programming language. These interactive features include job control, command line editing, command history and aliases. Each of these features is described in this manual.


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Useful Commands [Learn ubuntu/Linux with me -Day 3]

Boring Thoery:

What is a command?
A command can be given in any of these ways
  1. An executable program [files located in usr/bin directory] .
  2. Any C,C++,Python Program.
  3. Any builtin command [Ex:exit,cd]
    wait a sec how do i know if a command is builtin or not??
    There's a command which can do that for you.type <command>
    Ex: type cd  ,type exit (try these in your terminal)

    cam@hac3er:~$ type cd
    cd is a shell builtin
    cam@hac3er:~$ type exit
    exit is a shell builtin
    Interested to know more about builtins check these links
    Bash Manual 
  4. A Shell Function
  5. An alias

Interesting Part:


type – Display A Command's Type:

The type command is a shell builtin that displays the kind of command the shell will
execute, given a particular command name. It works like this:
Useage:type <command>
where “command” is the name of the command you want to examine. Here are some.Try these in your terminal
examples:

cam@hac3er:~$ type cd
cd is a shell builtin
cam@hac3er:~$ type exit
exit is a shell builtin
cam@hac3er:~$ type ls
ls is aliased to `ls --color=auto'
cam@hac3er:~$ type cp
cp is /bin/cp
cam@hac3er:~$ type mv
mv is /bin/mv

You can see different outputs which are self explanatory.cp is a command which is at a given location you can find cp at that location.

which – Display An Executable's Location: 

Usage:which <Executable>
 Just try these you'll understand

cam@hac3er:/$ which ls
/bin/ls
cam@hac3er:/$ which cd
cam@hac3er:/$ which cp
/bin/cp
cam@hac3er:/$ which mv
/bin/mv
cam@hac3er:/$ which exit
cam@hac3er:/$



Remember which works for only executables i mean the scripts written in a programming language.If you try to invoke it on builtins then it may throw an error or displays nothing.

help – Get Help For Shell Builtins:

You can get help from terminal by typing this command.you'll not understand a bit if you are a starter.
Usage:  help <comand>
bash has a built-in help facility available for each of the shell builtins. To use it, type “help” followed by the name of the shell builtin. For example:
cd is a builtin


cam@hac3er:/$ help cd
cd: cd [-L|[-P [-e]]] [dir]
    Change the shell working directory.
  
    Change the current directory to DIR.  The default DIR is the value of the
    HOME shell variable.
    .........................

    .........................(you'll get half a page of text)


Hey what if i need to get help for non builtins like cp or mkdir??
That would be a good question
Usage: Executable --help
Executable means like cp,mv,mkdir =>these are scripts remember??


cam@hac3er:/$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
  -p, --parents     no error if existing, make parent directories as needed
  -v, --verbose     print a message for each created directory
  -Z, --context=CTX  set the SELinux security context of each created
                      directory to CTX
      --help     display this help and exit
      --version  output version information and exit

Report mkdir bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'mkdir invocation'


cam@hac3er:/$ cp --help


Usage: cp [OPTION]... [-T] SOURCE DEST
  or:  cp [OPTION]... SOURCE... DIRECTORY
  or:  cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

Mandatory arguments to long options are mandatory for short options too.
  -a, --archive                same as -dR --preserve=all
      --attributes-only        don't copy the file data, just the attributes
      --backup[=CONTROL]       make a backup of each existing destination file
  -b                           like --backup but does not accept an argument
      --copy-contents          copy contents of special files when recursive
.............................trimmed I got a huge help text..................



man – Display A Program's Manual Page:

Most executable programs intended for command line use provide a formal piece of documentation called a manual or man page. A special paging program called man is used to view them.
Usage: 1)man <command>    Ex: man ls
            2)man section search_term    Ex: man 5 passwd



I didn't get the second syntax.
Then go through this boring theory but it's worth it
man uses less to display[remember ??less is used to view files,we discussed that in our previous posts]
man is divided into several sections so that is why you need to provide a section number for that
  Section       Contents
   1                 User commands
   2                 Programming interfaces kernel system calls
   3                 Programming interfaces to the C library
   4                 Special files such as device nodes and drivers
   5                 File formats
   6                 Games and amusements such as screen savers
   7                 Miscellaneous
   8                 System administration commands
Sometimes we need to look in a specific section of the manual to find what we are looking for.


apropos – Display Appropriate Commands:

Usage: apropros search_term
A simple search utility of command line.

cam@hac3er:/$ apropos floppy
fdformat (8)         - low-level format a floppy disk
mbadblocks (1)       - tests a floppy disk, and marks the bad blocks in the FAT
mformat (1)          - add an MSDOS filesystem to a low-level formatted floppy disk
mxtar (1)            - Wrapper for using GNU tar directly from a floppy disk

 

whatis – Display A Very Brief Description Of A Command:
The whatis program displays the name and a one line description of a man page
matching a specified keyword:
Usage: whatis cd

cam@hac3er:/$ whatis cd
cd: nothing appropriate.
cam@hac3er:/$ whatis ls
ls (1)               - list directory contents
cam@hac3er:/$ whatis mkdir
mkdir (1)            - make directories
mkdir (2)            - create a directory
cam@hac3er:/$ whatis cp
cp (1)               - copy files and directories
cam@hac3er:/$ whatis mv
mv (1)               - move (rename) files
cam@hac3er:/$



Creating Your Own Commands With alias:
Hey one thing that's irritating is that there is no command on my name :(
Let's create one.
One common thing i do is i often change my directory to desktop.. and give a command ls...this is a regular task i do.what if i combine both of them i.e changing directory and displaying it's contents.wow that's cool
Usage:alias yourname(somename)= <'command1;command2'>


You need to type properly and note that commands will be in between singlequotes
right click on a directory if you're not sure about the path of any directory.

cam@hac3er:/$ alias ajay='cd /home/cam/Desktop;ls;'
 

cam@hac3er:/$ ajay
1.html  2.py  comp_game.py   fb_pp.py  fb.py~  got.py~        Sublime Text 2
1.py    ajay  comp_game.py~  fb.py     got.py  ioredirection  test.py


cam@hac3er:~/Desktop$ type ajay
ajay is aliased to `cd /home/cam/Desktop;ls;'
 

cam@hac3er:~/Desktop$ unalias ajay
 

cam@hac3er:~/Desktop$ type ajay
bash: type: ajay: not found

 


To see all the aliases defined in the environment, use the alias command without
arguments.To remove that alias use:unalias name_of_the_alias


we'll it's too much for a post.Chek these links and keep typing in your terminal.
Bash Reference >>>Bash FAQ   >>>GNU Documentation >>Wikipedia

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Friday, July 5, 2013

Copy/Make/Move/Remove/Create Links-2 in Ubuntu/Linux[Learn ubuntu/Linux with me -Day 2



This is the continuation of my previous post

Click on the images for a better enlarged view.

How to remove files and directories from Terminal?


rm <file_name>
 
The above command deletes the file.

rm -r <dir_name>

The above command removes the directory.

I said i'll be telling you about links...remember hard & Symbolic links

first let's see the syntax for creating Links.


Before running down to the theory which i copied from a pdf i suggest you to go to these links,because you can get short and sweet answers.

>>Stackoverflow

>>askubuntu

>>wiki

Hard Links:


Hard links are the original Unix way of creating links, compared to symbolic links, which
are more modern. By default, every file has a single hard link that gives the file its name.
When we create a hard link, we create an additional directory entry for a file. Hard links
have two important limitations:
1. A hard link cannot reference a file outside its own file system. This means a link
may not reference a file that is not on the same disk partition as the link itself.
2. A hard link may not reference a directory.
A hard link is indistinguishable from the file itself. Unlike a symbolic link, when you list
a directory containing a hard link you will see no special indication of the link. When a
hard link is deleted, the link is removed but the contents of the file itself continue to exist
(that is, its space is not deallocated) until all links to the file are deleted.
It is important to be aware of hard links because you might encounter them from time to
time, but modern practice prefers symbolic links, which we will cover next.

Symbolic Links:

Symbolic links were created to overcome the limitations of hard links. Symbolic links
work by creating a special type of file that contains a text pointer to the referenced file or
directory. In this regard, they operate in much the same way as a Windows shortcut
though of course, they predate the Windows feature by many years ;-)
A file pointed to by a symbolic link, and the symbolic link itself are largely
indistinguishable from one another. For example, if you write some something to the
symbolic link, the referenced file is also written to. However when you delete a symbolic
link, only the link is deleted, not the file itself. If the file is deleted before the symbolic
link, the link will continue to exist, but will point to nothing. In this case, the link is said
to be broken. In many implementations, the ls command will display broken links in a
distinguishing color, such as red, to reveal their presence.
The concept of links can seem very confusing, but hang in there. We're going to try all
this stuff and it will, hopefully, become clear.

Example for Hard Links:



When thinking about hard links, it is helpful to imagine that files are made up of two
parts: the data part containing the file's contents and the name part which holds the file's
name. When we create hard links, we are actually creating additional name parts that all
refer to the same data part. The system assigns a chain of disk blocks to what is called an
inode, which is then associated with the name part. Each hard link therefore refers to a
specific inode containing the file's contents

On my desktop I've got a directory named ajay in which there are two directories named dir1 ,dir2 and a passwd file.View the above image in full screen.I've created hard links.
ls -l will give the number 4 to both passwd and passwd-hard file but to check wether they are different files or links we can use ls -li which gives us inode number.This number is same as you can see in the output.

Example for Symbolic Link:


The first example is pretty straightforward, we simply add the “-s” option to create a
symbolic link rather than a hard link. But what about the next two? Remember, when we
create a symbolic link, we are creating a text description of where the target file is
relative to the symbolic link. It's easier to see if we look at the ls output:
The listing for passwd-sym in dir1 shows that is it a symbolic link by the leading “l” in
the first field and that it points to “../passwd”, which is correct. Relative to the location of passwd-sym, passwd is in the directory above it. Notice too, that the length of the symbolic
link file is 9, the number of characters in the string “../passwd” rather than the length of the file to which it is pointing.
When creating symbolic links, you can either use absolute pathnames or relative path names.

In addition to regular files, symbolic links can also reference directories.



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Copy/Make/Move/Remove/Create Links-1 in Ubuntu/Linux[Learn ubuntu/Linux with me -Day 2]



Click on the images for a better enlarged view.


Looking at the title of post one may say ...Hey Ajay you are an idiot...Copy/paste this is the first task any user can do with a mouse click or simple drag and drop can do that. well I'll say by th end you'll understand.The commands which you are going to learn in this post will be used widely so just fire up terminal create dummy folders on your Desktop with some text files in them.

Command Description
mkdir directory... Why the heck did you put three dots?
Because you can repeat that..
What??
Here's the example
mkdir dir1 dir2 dir3 dir4
This will create the four directories.
cp item1 item2 item1 and item2 can be a file/directory
cp item1 item2 item3 directory
This will copy all items to the directory.
mv item1 item2 Moving and Renaming is done using this.
rm item Remove files
ln file link
ln -s item link
creates hard link
Creates symbolic link


 This is a bit complicated tutorial you need to do a lot of typing
mkdir:
The syntax is simple and self explanatory

cp:

copies files and directories

cp <somedir/somefile> .

did u see a dot at the end..?? copy a file from the given location to the current working directory.Check the image
dot/period is equivalent to current directory

you can do much more with copy


mv:

Renaming files and Moving the directories.

mv somefile somefile1

The above command does this ==> somefile is renamed to somefile1

mv somefile1 somedir1

this will move somefile1 to somedir1

Example :

1.cd Desktop ==>this will take you to Desktop
2.mkdir facebook ==>This will create facebook directory on your Desktop
3.cd facebook ==>This will take you inside facebook directory
4.mkdir profile friends job education relationship ==>will create 5 directories inside facebook directory
5.mv education friends job relationship profile ==>education friends job relationship directories are moved to profile directory
6.ls -l ==>Displays files/dirs in longer format[-l for longer].Now you can see only one directory inside facebook that's profile
7.cd profile ==>change your directory to profile.
8.ls -l displays files and dirs
9.cp -v /etc/passwd .
what the heck is this??
general syntax for copy ==> cp <from location of file> <to location>
cp is for copy ...v for verbose...
there is a password file @  /etc/passwd ==>from location
to location: . (period/dot stands for current location),So what's current location?it's facebook directory.
10.ls -l gives  profile dir and passwd file

The rest you can play around..
cp -i
i??i means interactive like if the to location has already that file cp -i will ask for your permisssion should it overwrite or not?if you type y it will overwrote else if you type n it will not overwrite the file.
cp -v will not tell you anything if a duplicate file exists,it just overwrites the file.


click the image for a better view and try these commands.


 This is too much for one post I'll post the rest in next post.Links are bit tough to understand...Play around with these.More you type more you learn.

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Thursday, July 4, 2013

ls command explained [Learn ubuntu/Linux with me -Day 2]



Click on the images for a better enlarged view.

Just Enter these commands in your Terminal.Description gives you an idea but I'll explain in detail.

Command Equivalent Long Command Description
ls -a ls --all Lists all Files including hidden files
ls -d ls --directory Ex: ls -ld /etc Try the above command and search on google.
ls -r ls --reverse Displays results in reverse order.
ls -S no long command Sort results by file size
ls -t no long command Sort by Modification time.
ls -l no long command. Displays results in long format

I'm in my home directory,check out those images.


How to hide files in ubuntu?
Some times you need to hide some files.In windows it's simple.How do you do it in ubuntu?
Rename the file /directory to .ajay or <dot>dirname[dot followed by a name].
it's as simple as that.File is gone.

How to view Hidden files in ubuntu?
Two ways
1.ctrl+h
2.Go to terminal ==>ls -a ==> displays hidden files.

Sort the files based on size and time of Modification

ls -S ==>Sort files based on Size[Capital or big S]

ls -t ===>Sort files based on time of Modification.


ls-l Explained:

ls -l ==> To show long listing information about the file/directory.
You get many things in the output.Each term is explained.You'll find similarity but not the exact thing.
1.drwxr-xr-x or -rw-rw-r-- 
d will be there for directories.
rwxr ==> these are permissions [read /write] .You don't need much but just remember.I'll cover this in detail.
2.Next you see a number ==>Number of hard links.

What the heck is hard link??Is there something called soft links?
Yes,yes there are hard links and soft links.I'll explain in detail in my next post.

3.cam ==> The user name of the file's owner. ***this will be your username.
4.cam ==> The name of the group which owns the file. *** this will be mostly username else it will be root.
5.4096 ==> Size of the file in bytes.
6.Jul 5 09:58 ==> Date and time of the file's last modification.
7.Desktop ==> Name of the file/directory.

*** Everthing will be different for you but the pattern remains mostly same.If you've any doubts let me know.

ls --help:

Last but not least ls --help ,there are many commands you can find them along with description .

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Learn ubuntu/Linux with me -Day 1

I've been working on ubuntu since 4 years or so,It's time to write a blog with some screen shots.There's a wonderful book which is free,if you've time then go ahead and read for yourself.
Let's dive in.
Problem that you'll face: 
Typing... you need to type a lot of commands don't use mouse it's not for hackers it's for  dummies,the solution for this is given at the end,but for now for very first time you need to type every command.

Click on the images for a better enlarged view



Type this to fire up your Terminal
ctrl+alt+t

or you can search Terminal from the dashboard.


Commands that we'll discuss today.Just enter this in your terminal.
Just enter these commands in terminal.I tried to explain with examples,check the screenshots for a better understanding
Just do these
Command What it does
date displays current date
cal displays current month calender
pwd Displays Present working Directory
cd <dirname> changes to the dirname directory
ls Lists all files and directories
file <filename> Displays the type of file
less <file_name> shows the content of file
***** <file name> ===> name of the file without '<' or '>' symbols,but the file should exist.
If your a noob then create a directory on your desktop.Inside it create a text file.
now use this command
cd Desktop/directoryname
now type ls in your terminal
ls will display the name of  the text file
**** file names/ dirnames shouldn't contain spaces..if they have space then you need to use double quotes. cd "ajay kumar" or ls "ajay kumar"


Frequently used:
pwd ==>present working Directory
cd ==> Change directory
ls ==> Lists all directories and files
Less Frequently used:
file <file name> ==> Determine File type
less <file name> ==> View Contents. 

In the screen shot below you'll see cam@hac3er:~$ This may vary for you,you may have some thing like this==> 'username@computer-name:~$'




cd Desktop ==> will take you to the Desktop directory.[ cd<space>dirname ]
dirname here is the directory name.The directory name is case sensitive.Desktop is different from desktop.

How the heck I know the directory name? Use the command ls It lists all the directories and files.
cd .. ==> takes you back to previous directory;
cd-- ==> will take you to home directory. 


Create a text file[ajay]/download an image file from internet
cd Desktop
file ajay
It will give you the type of file.
less ajay
The above command will display the content of that file.
To come out of less input q from keyboard

Don't name a file with space trust me on this.If you've a space in your directory or a file you need to use double quotes.

 

Solution for the Problem:
Use up and down arrows to move around the previous commands,Terminal Emulators can save upto 500 command history.
Once you move those arrows you can edit a part of command by pressing backspace.
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.