6 July 2015

Linux – Basic commands

When logged in into a Linux system you get access to a shell where applications and commands can be executed. When an application is called by its name the system searches for it in the current folder and the directories specified in “PATH”. To list all the environment variables and their values type env l less.

The shell provides us with some tricks to make working with it a little easier:

A list of useful commands

cp file1 file 2 Copies file1 to file2
cp -R directory1 directory2 Copies a whole folder recursively
cp -s file1 ffile2 Create a link file2 that points to file1
mv source destination Moves source to destination
mv -b Makes a backup of existing files at the destination so they wont be overwritten
mkdir directory1 Create a directory called directory1
mkdir -p parent/child Create a parent if it does not exist
rmdir directory1 Removes the directory directory1
rm file1 Remove the file file1
rm -r Remove directories and their contents recursively
find file1 Search for file1
find -iname Ignore case when searching
find -not Invert the search result and display those who do not match
cd path Go to the path
cd .. Go up to the parent directory
cd / Go to the root directory
pwd Print current working directory
df –total Shows the used and available space in all the file systems
ps r List all the active processes
whoami Show who is the current active user
cat Reads data from a file and shows its contents
more Splits a long text to different screens
uniq Filters duplicate rows from a files
wget Downloads a file from a network
grep Prints lines which matches a certain pattern
sort Sorts the contents per row in a file
wc Counts characters, words and rows

Pipes

Pipes chains an applications output to another applications input. Using that one can produce data in one link, filter it in another, sort it in a third and format in it a forth. For example:

ls -R / | grep .jpg | sort | markdown

ls -R / – Lists all files on the whole system
grep .jpg – Filters every file containing .jpg
sort – Sorts the files
markdown – Format the output with necessary to view it in a browser

Redirection

Acts somewhat like pipes with the difference that the destination of the data can be changed.  What normally is displayed on the screen is called STDOUT; STDERROR is a special channel for errors;  whats read from the keyboard is called STDIN. These channels can be treated as files as most other things in Linux.

STDIN can be redirected using <
STDOUT using >
you can also append to a file using >>
STDERROR using 2>

An example which saves the printout to a file instead of showing it on the screen:

ls -R / | grep .jpg | sort > jpglistfile