Linux – iExpertify https://www.iexpertify.com Upskill in 30 days, just 1 hour a day Thu, 15 Apr 2021 16:59:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://www.iexpertify.com/wp-content/uploads/2020/12/cropped-iExpertify-512x512-icon-32x32.png Linux – iExpertify https://www.iexpertify.com 32 32 Linux Commands for Beginners https://www.iexpertify.com/linux/linux-commands-for-beginners/ Tue, 15 Nov 2022 08:10:08 +0000 https://www.iexpertify.com/?p=4914 Reading Time: 6 minutes As we know that the Operating System is an important component of the computer. Linux operating system is open-source and community-developed for mainframes, servers. Linux is one of the widely accepted operating systems across the world. Searching Search for a specific pattern in a file with: grep [pattern] [file_name] Recursively search for a pattern in a directory:… Continue reading Linux Commands for Beginners

The post Linux Commands for Beginners appeared first on iExpertify.

]]>
Reading Time: 6 minutes
As we know that the Operating System is an important component of the computer. Linux operating system is open-source and community-developed for mainframes, servers. Linux is one of the widely accepted operating systems across the world.

Searching

Search for a specific pattern in a file with:

grep [pattern] [file_name]

Recursively search for a pattern in a directory:

grep -r [pattern] [directory_name]

Find all files and directories related to a particular name:

locate [name]

List names that begin with a specified character [a] in a specified location [/folder/location] by using the find command:

find [/folder/location] -name [a]

See files larger than a specified size [+100M] in a folder:

find [/folder/location] -size [+100M]

File Commands

List files in the directory:

ls

List all files (shows hidden files):

ls -a

Show directory you are currently working in:

pwd

Create a new directory:

mkdir [directory]

Remove a file:

rm [file_name] 

Remove a directory recursively:

rm -r [directory_name]

Recursively remove a directory without requiring confirmation:

rm -rf [directory_name]

Copy the contents of one file to another file:

cp [file_name1] [file_name2]

Recursively copy the contents of one file to a second file:

cp -r [directory_name1] [directory_name2]

Rename [file_name1] to [file_name2] with the command:

mv [file_name1] [file_name2]

Create a symbolic link to a file:

ln -s /path/to/[file_name] [link_name]

Create a new file:

touch [file_name]

Show the contents of a file:

more [file_name]

or use the cat command: This command used to create and view single or multiple files, and concatenate the files. It will consider one file output as another file input and print in the terminal or file.

cat [file_name]

Append file contents to another file:

cat [file_name1] >> [file_name2]

Display the first 10 lines of a file with:

head [file_name]

Show the last 10 lines of a file:

tail [file_name]

Encrypt a file:

gpg -c [file_name]

Decrypt a file:

gpg [file_name.gpg]

Show the number of words, lines, and bytes in a file:

wc

Hardware Information

Show bootup messages:

dmesg

See CPU information:

cat /proc/cpuinfo

Display free and used memory with:

free -h

List hardware configuration information:

lshw

See information about block devices:

lsblk

Show PCI devices in a tree-like diagram:

lspci -tv

Display USB devices in a tree-like diagram:

lsusb -tv

Show hardware information from the BIOS:

dmidecode

Display disk data information:

hdparm -i /dev/disk

Conduct a read-speed test on device/disk:

hdparm -tT /dev/[device]

Test for unreadable blocks on device/disk:

badblocks -s /dev/[device]

Directory Navigation

Move up one level in the directory tree structure:

cd ..

Change directory to $HOME:

cd

Change location to a specified directory:

cd /chosen/directory

File Compression

Archive an existing file:

tar cf [compressed_file.tar] [file_name]

Extract an archived file:

tar xf [compressed_file.tar]

Create a gzip compressed tar file by running:

tar czf [compressed_file.tar.gz]

Compress a file with the .gz extension:

gzip [file_name]

File Transfer

Copy a file to a server directory securely:

scp [file_name.txt] [server/tmp]

Synchronize the contents of a directory with a backup directory using the rsync command:

rsync -a [/your/directory] [/backup/] 

Users

See details about the active users:

id

Show last system logins:

last

Display who is currently logged into the system with the who command:

who

Show which users are logged in and their activity:

w

Add a new group by typing:

groupadd [group_name]

Add a new user:

adduser [user_name]

Add a user to a group:

usermod -aG [group_name] [user_name]

Temporarily elevate user privileges to superuser or root using the sudo command:

sudo [command_to_be_executed_as_superuser]

Delete a user:

userdel [user_name] 

Modify user information with:

usermod

Package Installation

List all installed packages with yum:

yum list installed

Find a package by a related keyword:

yum search [keyword]

Show package information and summary:

yum info [package_name]

Install a package using the YUM package manager:

yum install [package_name.rpm]

Install a package using the DNF package manager:

dnf install [package_name.rpm]

Install a package using the APT package manager:

apt-get install [package_name]

Install an .rpm package from a local file:

rpm -i  [package_name.rpm]

Remove an .rpm package:

rpm -e [package_name.rpm]

Install software from source code:

tar zxvf [source_code.tar.gz]
cd [source_code]
./configure
make
make install

Process Related

See a snapshot of active processes:

ps

Show processes in a tree-like diagram:

pstree

Display a memory usage map of processes:

pmap

See all running processes:

top

Terminate a Linux process under a given ID:

kill [process_id]

Terminate a process under a specific name:

pkill [proc_name]

Terminate all processes labelled “proc”:

killall [proc_name]

List and resume stopped jobs in the background:

bg

Bring the most recently suspended job to the foreground:

fg

Bring a particular job to the foreground:

fg [job]

List files opened by running processes:

lsof

Network

List IP addresses and network interfaces:

ip addr show

Assign an IP address to interface eth0:

ip address add [IP_address]

Display IP addresses of all network interfaces with:

ifconfig

See active (listening) ports with the netstat command:

netstat -pnltu

Show tcp and udp ports and their programs:

netstat -nutlp

Display more information about a domain:

whois [domain]

Show DNS information about a domain using the dig command:

dig [domain] 

Do a reverse lookup on domain:

dig -x host

Do reverse lookup of an IP address:

dig -x [ip_address]

Perform an IP lookup for a domain:

host [domain]

Show the local IP address:

hostname -I

Download a file from a domain using the wget command:

wget [file_name]

Linux Keyboard Shortcuts

Kill process running in the terminal:

Ctrl + C

Stop current process:

Ctrl + Z

The process can be resumed in the foreground with fg or in the background with bg.

Cut one word before the cursor and add it to clipboard:

Ctrl + W

Cut part of the line before the cursor and add it to clipboard:

Ctrl + U

Cut part of the line after the cursor and add it to clipboard:

Ctrl + K

Paste from clipboard:

Ctrl + Y

Recall last command that matches the provided characters:

Ctrl + R

Run the previously recalled command:

Ctrl + O

Exit command history without running a command:

Ctrl + G

Run the last command again:

!!

Log out of current session:

exit

File Permission

Chown command in Linux changes file and directory ownership.

Assign read, write, and execute permission to everyone:

chmod 777 [file_name]

Give read, write, and execute permission to owner, and read and execute permission to group and others:

chmod 755 [file_name]

Assign full permission to owner, and read and write permission to group and others:

chmod 766 [file_name]

Change the ownership of a file:

chown [user] [file_name]

Change the owner and group ownership of a file:

chown [user]:[group] [file_name]

Disk Usage

You can use the df and du commands to check disk space in Linux.

See free and used space on mounted systems:

df -h

Show free inodes on mounted filesystems:

df -i

Display disk partitions, sizes, and types with the command:

fdisk -l

See disk usage for all files and directory:

du -ah

Show disk usage of the directory you are currently in:

du -sh

Display target mount point for all filesystem:

findmnt

Mount a device:

mount [device_path] [mount_point]

SSH Login

Connect to host as user:
ssh user@host

Securely connect to host via SSH default port 22:

ssh host

Connect to host using a particular port:

ssh -p [port] user@host

Connect to host via telnet default port 23:

telnet host

The post Linux Commands for Beginners appeared first on iExpertify.

]]>
Linux File Permissions -chmod https://www.iexpertify.com/linux/linux-file-permissions/ Thu, 16 Jun 2022 13:50:33 +0000 https://www.iexpertify.com/?p=4826 Reading Time: 7 minutes Linux is a multi-operating system that can be accessed through numerous users concurrently. So, it has to be authenticated to ensure people from accessing other confidential files. Linux can also be used in mainframes and servers without any modifications. It uses the concept of ownership and permissions to enhance the security of the directories and… Continue reading Linux File Permissions -chmod

The post Linux File Permissions -chmod appeared first on iExpertify.

]]>
Reading Time: 7 minutes

Linux is a multi-operating system that can be accessed through numerous users concurrently. So, it has to be authenticated to ensure people from accessing other confidential files. Linux can also be used in mainframes and servers without any modifications. It uses the concept of ownership and permissions to enhance the security of the directories and files. 

Linux File Permissions

Types of permissions

Every directories and file in Linux have three basic permission types. They are discussed as follows:

#1 Read Permission

The read permission enables you to open and read a file. For a directory, the read permission enables the user to list the contents of the directory.

#2 Write Permission

The write permission allows the user to modify the file and write new data to the file. For a directory, the write permission allows the user to modify the content of the directory. The user can add, remove, or rename files that belong to a particular directory. 

#3 Execute Permissions

The execute permission allows the user to execute the file as a shell script or a program. For the directory, the execute permission enables the user to access the files in a directory and enter it by using the cd command but it does not allow to list the content.

Viewing the permissions

The view permission allows the user to check the directory or file in the GUI file manager or by reviewing the output using the command given below.

ls -l 

Permissions groups

Every directory and file on Linux is owned by a specific user and group and are defined separately as three user based permission groups. They are as follows:

# User

A user is a person who owns the directory or file. By default, the user who creates the file or directory will be the owner. 

# Group

The user group that owns the directory or file will not affect the actions of other users. All the users who belong to the group that owns the directory or file will have the same permission to access the file or directory.

# Other

The user who is not the owner of the directory or file and doesn’t belong to the same group of the directory or file. Simply, if we set the permission for the ‘other’ category, by default it will affect everyone. 

If you want to view the users on the system, you can view the user using the command below:

cat /etc/passwd

Similarly, you can view the group on the system by using the command below:

cat /etc/group

-rw-rw-r– is a code that represents the permissions given to the owner, user group, and the world.

Here, the ‘-’ represents the selected file. For the directory, it is denoted as ‘d’. 

The characters are simple to remember and understand.

  • r- read permission
  • w- write permission
  • x- execute permission
  • _- no permission

The first part of the code ‘rw-’ represents the owner can read the file, write the file, but cannot execute the file since the execute bit is set to ‘-’. Several Linux distributions such as CentOS, Ubuntu, Fedora, etc. will add users to the group of the same group name as the username. 

The second part of the code ‘rw-’ represents for the user group and group members can read the file, write the file.

The third part of the code ‘r–’ represents any user and the user can only read the file.

Changing file permission using chmod

With the help of the change mode ‘chmod’ command, we can set the permissions such as read, write, and execute on a directory or file for the owner, user, and the group.

chmod <permission-number> <file-name>

Here, the permission number is calculated by using the assigned values for r, w, and x. The basic permission number includes three digits. Some special cases can use four digits as a permission number. 

There are two ways to use the commands. They are as follows: 

1. Numeric mode

In a numeric mode, file permissions do not denote as characters but as a three-digit octal number. The following table provides the numbers for all permission types.

NumberCharacter of SymbolPermission Type
0No permission
1–xExecute
2-w-Write
3-wxWrite+Execute
4r–Read
5r-xRead+Execute
6rw-Read+Write
7rwxRead+Write+Execute

For example, see the command below.

$ chmod 764 sample

ls -l sample

rwxrw-r-- 1 iExpertify iExpertify 20 June 20 06:00 sample

chmod 764 and checking permission. In the above command, we have changed the file permissions to 764. 764 represents the following:

  • The owner can read, write, and execute
  • The user group can read and write
  • Any user can only read

2. Symbolic mode

In this mode, we can change permissions for all three owners. We can modify the permissions of a specific owner. With the use of mathematical symbols, we can modify the file permissions.

OperatorDescription
+Adds permission to access directory or files
Removes permissions
=Sets permission and overrides the permissions set earlier

Let’s see the example:

Current file

ls -l sample

-rw-rw-r-- 1 iExpertify iExpertify 22 2020-06-29 13:45 sample?

Setting permission to other users

$ chmod 0=rwx sample

$ ls -l sample

-rw-rw-rwx 1 iExpertify iExpertify 22 2020-06-29 13:45 sample

Adding execute permission to the user group

$ chmod g+x sample

$ ls -l sample

-rw-rwxrwx 1 iExpertify iExpertify 22 2020-06-29 13:45 sample?

Removing read permission for the user

$ chmod u-r sample

$ ls -l sample

--w-rwxrwx 1 iExpertify iExpertify 22 2020-06-29 13:45 sample

Changing ownership and group

For changing the ownership of a directory or file, use the command below:

chown user

If you want to change the user along with the group for a directory or file, use the command below

chown user: group filename

If you wish to change group owner only, use the command below

chgrp group_name filename

Here, chgrp represents for change group

Advanced permissions

The special permissions that are used to access directories or files are as following:

  • _ – It represents there are no special permissions.
  • d- It represents the directory.
  • l-  It represents the symbolic link of a directory or a file.
  • t- It represents the sticky bit permissions. It represents ‘t’ in the executable portion of all user permissions.
  • s- It indicates the setuid or setgid permissions. It represents ‘s’ in the read portion of the owner or group permissions.

Setuid or setgid special permissions

The setuid or setgid permissions are used to assign the system to run an executable as the owner with the owner’s permissions. We can assign this permission by explicit defining permissions.

The character that represents the setuid or setgid is ‘s’. To set the setuid or setgid bit on file1.sh, use the command below:

chmod g+s file1.sh

Be careful while using setuid or setgid permissions. If you assign the permissions incorrectly, then your system goes to intrusion.

Sticky bit special permissions

The sticky bit can be useful in a shared environment because when it is assigned to the permissions on a directory it sets permissions for the file owner only to rename or delete the file.

The character for the sticky bits is ‘t’. To set the sticky bits on a directory, use the command below:

chmod+t dir1

Tip

  • The file /etc/group contains all the groups defined in the system
  • You can use the command “groups” to find all the groups you are a member of
  • You can use the command newgrp to work as a member a group other than your default group
  • You cannot have 2 groups owning the same file.
  • You do not have nested groups in Linux. One group cannot be sub-group of other
  • x- eXecuting a directory means Being allowed to “enter” a dir and gain possible access to sub-dirs
  • There are other permissions that you can set on Files and Directories which will be covered in a later advanced tutorial

Summary:

  • Linux being a multi-user system uses permissions and ownership for security.
  • There are three user types on a Linux system viz. User, Group and Other
  • Linux divides the file permissions into read, write and execute denoted by r,w, and x
  • The permissions on a file can be changed by ‘chmod’ command which can be further divided into Absolute and Symbolic mode
  • The ‘chown’ command can change the ownership of a file/directory. Use the following commands: chown user file or chown user:group file
  • The ‘chgrp’ command can change the group ownership chrgrp group filename
  • What does x – eXecuting a directory mean? A: Being allowed to “enter” a dir and gain possible access to sub-dirs.

The post Linux File Permissions -chmod appeared first on iExpertify.

]]>
Grep Regex Example Linux https://www.iexpertify.com/linux/grep_regex_example_linux/ Tue, 21 Dec 2021 21:12:35 +0000 https://www.iexpertify.com/?p=3262 Reading Time: 4 minutes What are Regular Expressions? Regular expressions are special characters which help search data, matching complex patterns. Regular expressions are shortened as 'regexp' or 'regex'. Types of Regular expressions For ease of understanding let us learn the different types of Regex one by one. Basic Regular expressions Interval Regular expressions Extended regular expressions Summary Click here if the video is not accessible Basic Regular expressions Some of the commonly used commands with Regular expressions are tr, sed, vi and grep. Listed below are some of the basic Regex. Symbol Descriptions . replaces any character ^ matches start of string $ matches end of string * matches up zero or more times the preceding character \ Represent special characters () Groups regular expressions ? Matches up exactly one character Let's see an example. Execute cat sample to see contents of an existing file Search for content containing letter 'a'. '^' matches the start of a string. Let's search for content that STARTS with a Only lines that start with character are filtered. Lines which do not contain the character 'a' at the start are ignored. Let's look into another example - Select only those lines that end with t using $ Interval Regular expressions These expressions tell us about the number of occurrences of a character in a string. They are Expression Description {n} Matches the preceding character appearing 'n' times exactly {n,m} Matches the preceding character appearing 'n' times but not more than m {n, } Matches the preceding character only when it appears 'n' times or more Example: Filter out all lines that contain character 'p' We want to check that the character 'p' appears exactly 2 times in a string one after the other. For this the syntax would be: cat sample | grep -E p\{2} Note: You need to add -E with these regular expressions. Extended regular expressions These regular expressions contain combinations of more than one expression. Some of them are: Expression Description \+ Matches one or more occurrence of the previous character \? Matches zero or one occurrence of the previous character Example: Searching for all characters 't' Suppose we want to filter out lines where character 'a' precedes character 't' We can use command like cat sample|grep "a\+t" Brace expansion The syntax for brace expansion is either a sequence or a comma separated list of items inside curly braces "{}". The starting and ending items in a sequence are separated by two periods "..". Some examples: In the above examples, the echo command creates strings using the brace expansion. Summary: Regular expressions are a set of characters used to check patterns in strings They are also called 'regexp' and 'regex' It is important to learn regular expressions for writing scripts Some basic regular expressions are: Symbol Descriptions . replaces any character ^ matches start of string $ matches end of string Some extended regular expressions are: Expression Description \+ Matches one or more occurrence of the previous character \? Matches zero or one occurrence of the previous character Some interval regular expressions are: Expression Description {n} Matches the preceding character appearing 'n' times exactly {n,m} Matches the preceding character appearing 'n' times but not more than m {n, } Matches the preceding character only when it appears 'n' times or more The brace expansion is used to generate strings. It helps in creating multiple strings out of one.  

The post Grep Regex Example Linux appeared first on iExpertify.

]]>
Reading Time: 4 minutes

What are Regular Expressions?

Grep Regex is one of the most popular command-line utilities to find and search strings in a text file.

Using the grep command with regular expressions makes it even more powerful.

Regular expressions come in the picture when you want to search for a text containing a particular pattern.

It simplifies your search operation by searching the patterns on each line of the file.

Types of Regular expressions

For ease of understanding let us learn the different types of Regex one by one.

Basic Regular expressions

Some of the commonly used commands with Regular expressions are tr, sed, vi and grep. Listed below are some of the basic Regex.

SymbolDescriptions
.replaces any character (single character)
^matches start of string
$matches end of string
*matches up zero or more times the preceding character
\Represent special characters
()Groups regular expressions
?Matches up exactly one character

Let’s create a sample test.txt file with the following content:

cat test.txt

Output:

This record ends in 2021
2021 is the start of the record

2021
2020

This record ends in 2020
2020 is the start of the record

For example, find all the lines which end with the word 2021:

grep "2021$" test.txt

You should see the following output:

This record ends in 2021

2021

Next, find all the lines which start and end with the word 2021:

grep "^2021$" test.txt

You should see the following output:

2021

For example, find all the lines which end with the word 2020 or 2021(The dot allows any single character in the place):

grep "202.$" test.txt

You should see the following output:

This record ends in 2021

2021

This record ends in 2020

2020

Now, lets display all the lines that start with the string balaram:

grep "^2021" test.txt

You should see the following output:

2021 is the start of the record
2021

Next, find the number of blank lines in the file test.txt:

grep "^$" test.txt

You should see the following output:

<3 empty lines>

Interval Regular expressions

These expressions tell us about the number of occurrences of a character in a string. They are

ExpressionDescription
{n}Matches the preceding character appearing ‘n’ times exactly
{n,m}Matches the preceding character appearing ‘n’ times but not more than m
{n, }Matches the preceding character only when it appears ‘n’ times or more

Example:

Filter out all lines that contain character ‘p’

We want to check that the character ‘p’ appears exactly 2 times in a string one after the other. For this the syntax would be:

cat sample | grep -E p\{2}

Note: You need to add -E with these regular expressions.

Extended regular expressions

These regular expressions contain combinations of more than one expression. Some of them are:

ExpressionDescription
\+Matches one or more occurrence of the previous character
\?Matches zero or one occurrence of the previous character

Example:

Searching for all characters ‘t’

Suppose we want to filter out lines where character ‘a’ precedes character ‘t’

We can use command like

cat sample|grep "a\+t"

The regular expression (\) used to search for special characters.

Let’s create a sample test.txt file with the following contents:

cat test.txt

Output:

1.1.1.1
1a1a1a1
1b1c1d1

Now, search for all the lines which matches the pattern “1.1.1.1“:

grep "1.1.1.1" test.txt

This command does not show the proper result as “.” matches any single character:

1.1.1.1
1a1a1a1
1b1c1d1

You can use the regular expression “\” to resolve this issue:

grep "1\.1\.1\.1" test.txt

Output:

1.1.1.1

Brace expansion

The syntax for brace expansion is either a sequence or a comma separated list of items inside curly braces “{}”. The starting and ending items in a sequence are separated by two periods “..”.

Some examples:

In the above examples, the echo command creates strings using the brace expansion.

Let’s create a sample test.txt file with the following contents:

cat test.txt

Output:

apple
appple
appppple

Now, search for all the lines which match a character “p” two times:

grep -E "ap{2}l" test.txt

You should see the following output:

apple

Next, search for all the lines which match a character “p” two or more times:

grep -E "ap{2,}l" test.txt

You should see the following output:

apple
appple
appppple

Next, search for all the lines which match a character “p” two or three times:

grep -E "ap{2,3}l" test.txt

You should see the following output:

apple
appple

Square bracket expansion

The regular expression [] can be used to match any one character found within the bracket group.

search for all the lines which match any range character found within the “test” group.

grep "test[x-z]" test.txt

You should see the following output:

testx
testy
testz

The post Grep Regex Example Linux appeared first on iExpertify.

]]>
Input Redirection in Linux/Unix Examples https://www.iexpertify.com/linux/input-output-redirection-in-linux-unix-examples/ Sun, 10 Oct 2021 23:10:36 +0000 https://www.iexpertify.com/?p=3260 Reading Time: 2 minutes What is Redirection?Redirection is a feature in Linux such that when executing a command, you can change the standard input/output devices. The basic workflow of any Linux command is that it takes an input and give an output. The standard input (stdin) device is the keyboard. The standard output (stdout) device is the screen. With redirection, the above standard input/output can be changed. In this tutorial, we will learn- Output Redirection Input redirection File Descriptors (FD) Error Redirection Why Error Redirection? Examples Click here if the video is not accessible Output Redirection The '>' symbol is used for output (STDOUT) redirection. Example: ls -al > listings Here the output of command ls -al is re-directed to file "listings" instead of your screen. Note: Use the correct file name while redirecting command output to a file. If there is an existing file with the same name, the redirected command will delete the contents of that file and then it may be overwritten." If you do not want a file to be overwritten but want to add more content to an existing file, then you should use '>>' operator. You can redirect standard output, to not just files, but also devices! $ cat music.mp3 > /dev/audio The cat command reads the file music.mp3 and sends the output to /dev/audio which is the audio device. If the sound configurations in your PC are correct, this command will play the file music.mp3 Input redirectionThe '<' symbol is used for input(STDIN) redirection Example: The mail program in Linux can help you send emails from the Terminal. You can type the contents of the email using the standard device keyboard. But if you want to attach a File to email you can use the input re-direction operator in the following format. Mail -s "Subject" to-address < Filename This would attach the file with the email, and it would be sent to the recipient. The above examples were simple. Let's look at some advance re-direction techniques which make use of File Descriptors. File Descriptors (FD) In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files. Every File has an associated number called File Descriptor (FD). Your screen also has a File Descriptor. When a program is executed the output is sent to File Descriptor of the screen, and you see program output on your monitor. If the output is sent to File Descriptor of the printer, the program output would have been printed. Error Redirection Whenever you execute a program/command at the terminal, 3 files are always open, viz., standard input, standard output, standard error. These files are always present whenever a program is run. As explained before a file descriptor, is associated with each of these files. File File Descriptor Standard Input STDIN 0 Standard Output STDOUT 1 Standard Error STDERR 2 By default, error stream is displayed on the screen. Error redirection is routing the errors to a file other than the screen. Why Error Redirection? Error re-direction is one of the very popular features of Unix/Linux. Frequent UNIX users will reckon that many commands give you massive amounts of errors. For instance, while searching for files, one typically gets permission denied errors. These errors usually do not help the person searching for a particular file. While executing shell scripts, you often do NOT want error messages cluttering up the normal program output. The solution is to re-direct the error messages to a file. Example 1 $ myprogram 2>errorsfile Above we are executing a program names myprogram. The file descriptor for standard error is 2. Using "2>" we re-direct the error output to a file named "errorfile" Thus, program output is not cluttered with errors. Example 2 Here is another example which uses find statement - find . -name 'my*' 2>error.log Using the "find" command, we are searching the "." current directory for a file with "name" starting with "my" Example 3 Let's see a more complex example, Server Administrators frequently, list directories and store both error and standard output into a file, which can be processed later. Here is the command. ls Documents ABC> dirlist 2>&1 Here, which writes the output from one file to the input of another file. 2>&1 means that STDERR redirects to the target of STDOUT (which is the file dirlist) We are redirecting error output to standard output which in turn is being re-directed to file dirlist. Hence, both the output is written to file dirlist Summary Each file in Linux has a corresponding File Descriptor associated with it The keyboard is the standard input device while your screen is the standard output device ">" is the output redirection operator. ">>" appends output to an existing file "<" is the input redirection operator ">&"re-directs output of one file to another. You can re-direct error using its corresponding File Descriptor 2.  

The post Input Redirection in Linux/Unix Examples appeared first on iExpertify.

]]>
Reading Time: 2 minutes

Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file. As the greater-than character > is used for output redirection, the less-than character < is used to redirect the input of a command.

We may want a file to be the input for a command that normally wouldn’t accept a file as an option. This redirecting of input is done using the “<” (less-than symbol) operator.

Below is an example of sending a file to somebody, using input redirection.

> mail john.dba@organization.com < sample_ddl

This reads a bit more difficult than the beginner’s cat file | mail someone, but it is of course a much more elegant way of using the available tools.

File Descriptors (FD)

In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files. Every File has an associated number called File Descriptor (FD).

Your screen also has a File Descriptor. When a program is executed the output is sent to File Descriptor of the screen, and you see program output on your monitor. If the output is sent to File Descriptor of the printer, the program output would have been printed.

Whenever you execute a program/command at the terminal, 3 files are always open, viz., standard input, standard output, standard error.

FileFile Descriptor
Standard Input STDIN0
Standard Output STDOUT1
Standard Error STDERR2

Following is a complete list of commands which you can use for redirection −

Sr.No.Command & Description
1cmd > file Output of cmd is redirected to file
2cmd < file Program cmd reads its input from file
3cmd >> file Output of cmd is appended to file
4n > file Output from stream with descriptor n redirected to file
5n >> file Output from stream with descriptor n appended to file
6n >& m Merges output from stream n with stream m
7n <& m Merges input from stream n with stream m
8<< tag Standard input comes from here through next tag at the start of line
9| Takes output from one program, or process, and sends it to another

The post Input Redirection in Linux/Unix Examples appeared first on iExpertify.

]]>
Linux vs Unix https://www.iexpertify.com/linux/linux-vs-unix/ Wed, 28 Apr 2021 13:03:00 +0000 https://www.iexpertify.com/?p=4807 Reading Time: 8 minutes An operating system is the most important software that a computer cannot work without. What is Unix? Unix is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in the 1970s at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and others. There are different versions of Unix, and some of the simplified versions are –… Continue reading Linux vs Unix

The post Linux vs Unix appeared first on iExpertify.

]]>
Reading Time: 8 minutes

An operating system is the most important software that a computer cannot work without.

What is Unix?

Unix is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in the 1970s at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and others. There are different versions of Unix, and some of the simplified versions are – Sun Solaris, GNU, and macOS X.

It began as a one-man project under the leadership of Ken Thompson of Bell Labs. It went on to become most widely used operating systems. Unix is a proprietary operating system.

The Unix OS works on CLI (Command Line Interface), but recently, there have been developments for GUI on Unix systems. Unix is an OS which is popular in companies, universities big enterprises, etc.

What are the features of the Unix operating system?

Some of the prominent features of Unix are as follows:

  • Unix distinguishes itself from its predecessors as the first portable operating system: almost the entire operating system is written in the C programming language, which allows Unix to operate on numerous platforms.
  • It can be used as the master control program in workstations and servers.
  • Hundreds of commercial applications are available
  • In its heydays, UNIX was rapidly adopted and became the standard OS in universities.
  • It was the first operating system that was written in a high-level language and was easy to port to another machine with the least adaptation.
  • It is a multi-user system where the same resources can be shared by multiple users.
  • The functionality of Unix gets extended through a standard programming interface.
  • Unix offers multi-tasking, which means each user can carry out several processes simultaneously.

Unix Architecture

Unix architecture consists of several layers mentioned below:

  • Hardware – It consists of all the hardware related information.
  • Kernel – It is the heart of the operating system that interacts with hardware. It also handles tasks like memory management, task management, file management, power management, etc.
  • Shell – This layer basically processes your request. When a user type commands at the terminal, Shell interprets the commands and calls the program a user needs. The commands that are used are -mv, cat, grep, id, wc, cp, nroff, etc.
  • Application Layer – The application layer includes graphics programs, database management programs, word processors, commands, etc. These programs, as a single unit provide an application to end-users.

What is Linux?

Linux is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged in a Linux distribution.

The Linux OS relays instructions from an application from the computer’s processor and sends the results back to the application via the Linux OS. It can be installed on a different type of computers mobile phones, tablets video game consoles, etc.

The development of Linux is one of the most prominent examples of free and open source software collaboration. Today many companies and similar numbers of individuals have released their own version of OS based on the Linux Kernel.

What are the features of Linux?

  • Supports multitasking
  • It can easily co-exists along with other Operating systems.
  • It can run multiple user programs
  • Individual accounts are protected because of appropriate authorization
  • Linux is a replica of UNIX but does not use its code.
  • Programs might be consist of more than one process, and each process can have multiple threads

Architecture of Linux

The Linux operating system consists of four layers – Hardware, Kernel, Shell, and Application layer. Let us find out more about these layers:

  • Hardware – The hardware layer consists of all the physical devices that are attached to the system. Some of the examples are -RAM, motherboard, CPU, Hard disk drive, etc.
  • Kernel – Kernel is the core layer of the Linux operating system that establishes the direct interaction with the hardware.
  • Shell – This layer acts as an interface that takes inputs from the user and sends it to the kernel and vice versa.
  • Applications – These applications are the utility programs that run on the shell. Some of these applications are -web browsers, media player, text editor, etc.

Differences – Linux vs Unix

Are Linux and Unix the same thing? No, they are not. Unix and Linux are different from each other, but yes they do share a relationship because Linux is derived from Unix. Linux system is a continuation of the Unix design. Is Linux better than Unix? Readout more to find out which is better and helpful for your working style.

Basis of Difference Linux Unix
Source Code The source code is accessible to the general public The source code is not available to anyone
Kernel Follows monolithic kernel approach Can be monolithic, microkernel, or hybrid
Portability It is portable and can be booted from a USB stick It is not portable
Cost Linux is freely distributed and can be downloaded in different ways. Paid versions are also available Different versions of Unix have different prices depending upon the type of vendor.
Development Linux is open-source where thousands of programmers can collaborate online and contribute to its development. The different versions of Unix are developed by AT & T and also by commercial vendors
Text Interface BASH is the Linux default shell and supports multiple command interpreters Originally made to work in Bourne Shell. However, it is now compatible with many others software.
GUI Linux has two GUI – KDE and Gnome. Common desktop environment and Gnome
Threat detection Threat detection is fast in Linux because it is community-driven. If any user posts about a threat, a team of developers start resolving it. Unix users have to wait a little longer for a bug to get fixed
Architecture It is available for more than twenty different CPUs including ARM It is available for PA-RISC and Itanium machines
Supported file systems xfs, nfs, cramfsm ext 1 to 4, ufs, devpts, NTFS. zfs, hfx, GPS, xfs, vxfs
Versions Different Versions of Linux are Redhat, Ubuntu, OpenSuse, etc Different Versions of Unix are HP-UX, AIS, BSD, etc

Linux vs Unix: Commands

There are certain differences between the shell commands of Unix and Linux. The commands of Linux and Unix may look similar but they are not the same.

Solaris vs Linux

Solaris also called Oracle Solaris belongs to the Unix family. Linux is compatible with more system architecture than Solaris does and therefore, Linux is more portable. Solaris seems better when it comes to hardware integration and stability. Linux has a faster development rate as compared to Solaris. 

macOS vs Linux 

macOS is a Unix OS that has its Kernel called XNU. It is used in one of the most reliable PC’s ie. Apple’s computers. macOS is relatively easy to install. Linux is cheaper and more flexible. macOS uses the HFS+ file system, but Linux uses ext4.

Limitation of Linux

  • There is no standard edition of Linux.
  • It has patchier support for drivers that may cause malfunctioning of the entire system.
  • Linux is not very easy to use at least for new users.
  • Many programs that we use for Windows like Microsoft Office will run on Linux with the help of a complicated emulator
  • Linux may be suitable for a corporate user but much harder for a home setting.

Limitations of Unix

  • Unix is designed for a slow computer system; it can’t offer fast performance.
  • It has an unfriendly and non-mnemonic user interface
  • Shell interface can be risky because a single typing error can destroy files.
  • It lacks consistency because its versions are slightly different on various machines.
  • Unix does not give any assured hardware interrupt response time.Is Linux better than Unix?

Linux has gained more popularity because it is more flexible and free when compared to Unix. They are not the same but very much similar, even the commands in each distribution also vary. There are studies that show Linux is growing at a faster rate than any other operating system and it is believed that in the coming future it may leave Unix installation far behind.

Future of Linux and Unix

History of Linux – Linux was introduced in 1991 and got popular in a short period of time. Originally, it was designed only for intel 386, but today it runs on every machine. It has millions of users, and it is doing well in the embedded systems, industrial automation, cloud computing, mobile devices, robotics, etc. it is definitively less popular for the desktop system industry.

Talking about its future, Linus Torvalds, the founder of Linux, has declared some developments and improvements in the features that will be compatible with a wider number of systems.

Unix is an old OS, and its advocates are continuously developing new specifications to make it compatible with the coming era of computing.

The post Linux vs Unix appeared first on iExpertify.

]]>
Piping – using | symbol https://www.iexpertify.com/linux/piping-using-symbol/ Fri, 09 Apr 2021 10:03:33 +0000 https://www.iexpertify.com/?p=12853 Reading Time: 3 minutes Pipelines (|) We often want to take the output of one command and pass it on to another. The standard way of performing this is using a pipeline, referred to as pipe, or pipeing the output. The pipe is a vertical bar ‘|’. On a standard US keyboard this shares the same ‘\’ key, but… Continue reading Piping – using | symbol

The post Piping – using | symbol appeared first on iExpertify.

]]>
Reading Time: 3 minutes

Pipelines (|)

We often want to take the output of one command and pass it on to another. The standard way of performing this is using a pipeline, referred to as pipe, or pipeing the output.

The pipe is a vertical bar ‘|’. On a standard US keyboard this shares the same ‘\’ key, but is sometimes located above the RETURN key. On a standard UK keyboard this is normally found at the bottom left of the keyboard and is typed by using shift and the ‘\’ key. On other European keyboards this may be on one of the number keys (e.g. Alt-Gr 6).

The first command to run is listed first followed by the pipe symbol and then followed by the second command. Any output from the first command is then used as input to the second command. We can search, sort, slice, dice, and transform data stored in files in many different ways. A pipe (also called a pipeline) is a powerful shell feature that allows you to p ump the output of one program directly into another.

For example to sort a basic directory listing by name the ls command is piped through the sort command.

ls | sort

The output can be passed through a number of commands by using a pipe through each one. The full command string is referred to as a pipeline.

ls | sort | more

In the below example, we use sort and uniq command to sort a file and print unique values.

$ sort record.txt | uniq 

This will sort the given file and print the unique values only.

Use ls and find to list and print all lines matching a particular pattern in matching files. This command select files with .parm extension in the given directory and search for pattern like “program” in the below example and print those which have word table1 in them.

$ ls -l | find ./ -type f -name "*.parm" -exec grep "table1" {} \;

The command below would take the output from the cat command (listing the contents of a file). and send them to the grep command. The grep command searches for each occurrence of the word High in it’s input. The grep command output would now consist of each line within the file that contained the word High. This output is now sent to the wc command where the wc command with the -l option prints the total number of lines contained in it’s input. 

cat sample.text | grep "High" | wc -l

The post Piping – using | symbol appeared first on iExpertify.

]]>
Redirect output – using > symbol https://www.iexpertify.com/linux/redirect-output-using-symbol/ Fri, 09 Apr 2021 09:28:57 +0000 https://www.iexpertify.com/?p=12849 Reading Time: 3 minutes The > symbol is used to redirect the output of a command. Redirecting stdout, stdin and stderr (> <) Unless a command is piped into another the output normally goes to the standard output (stdout) which is normally the screen. The input is normally taken from standard input (stdin) which is normally the keyboard. To automate processes… Continue reading Redirect output – using > symbol

The post Redirect output – using > symbol appeared first on iExpertify.

]]>
Reading Time: 3 minutes

The > symbol is used to redirect the output of a command.

Redirecting stdout, stdin and stderr (> <)

Unless a command is piped into another the output normally goes to the standard output (stdout) which is normally the screen. The input is normally taken from standard input (stdin) which is normally the keyboard. To automate processes it is sometimes required to change this so that for example the output from a command is sent to a file or the printer, or the input to a command is taken from a file. This is done by redirecting the stdout and stdin streams.

Redirect command output (stdout) into a file

command > filename

Redirect error output (stderr) to a file

command 2> filename


It is also possible to write both stdout and the standard error stream to the same file. This can be achieved by redirecting the error data stream to the stdout data stream using 2>&1.

command >output.file 2>&1
output of grep command written into c112.txt file

Using a Temporary File

Sometimes the output would have to be redirected to a temporary file and then renamed to the required name. the sort from file1 cannot be directly stored in file1

sort file1 >/temp/tmp$$
mv /tmp/tmp$$ file1

The file ending in $$ will actually be created by the system with a unique number. This is useful for temporary files as it prevents you overwriting a temporary file in use by a different process.

The >> symbol

The single greater-than (>) can be replaced by double greater-than symbol (>>) if you would like the output to be appended to the file rather than to overwrite the file.

The tee command

Sometimes it is necessary for someone to monitor the output of the command but also for it to be duplicated into a file for logging purposes or to perform further processing on.

The tee command is used within a pipeline and whatever input it receives it both puts outputs into a file and forwards on the pipeline.

command | tee file1

The line above will take any output from the command and put a copy in file1 as well as sending it to the screen. This could be combined further by allowing the output to be further processed by another command. The tee command can be used any number of times in a pipeline. If you want tee to append to a file rather than overwrite it the -a option is used.

command1 | tee file1 | command2

For example, let us use cat, grep, tee and wc command to read the particular entry from user and store in a file and print line count.

$ cat result.txt | grep "iExpertify" | tee -a file2.txt | wc -l

This command select iExpertify and store them in file2.txt and print total number of lines matching iExpertify

The post Redirect output – using > symbol appeared first on iExpertify.

]]>
Using wildcards in Linux https://www.iexpertify.com/linux/using-wildcards-in-linux/ Fri, 09 Apr 2021 01:27:07 +0000 https://www.iexpertify.com/?p=12841 Reading Time: 2 minutes Wildcards (also referred to as meta characters) are symbols or special characters that represent other characters. You can use them with any command such as ls command or rm command to list or remove files matching a given criteria, receptively. There are three main wildcards in Linux: An asterisk (*) – matches one or more occurrences of any character, including no character.… Continue reading Using wildcards in Linux

The post Using wildcards in Linux appeared first on iExpertify.

]]>
Reading Time: 2 minutes

Wildcards (also referred to as meta characters) are symbols or special characters that represent other characters. You can use them with any command such as ls command or rm command to list or remove files matching a given criteria, receptively.

There are three main wildcards in Linux:

  • An asterisk (*) – matches one or more occurrences of any character, including no character.
  • Question mark (?) – represents or matches a single occurrence of any character. so, it matches exactly one charecter
  • Bracketed characters ([ ]) – matches any occurrence of character enclosed in the square brackets. It is possible to use different types of characters (alphanumeric characters): numbers, letters, other special characters etc.

We use these wildcards typically in ls and rm commands for example to list all txt or html files in the folder:

ls *.txt *.html

to delete all txt files in the folder:

rm *.txt

Using first example we can get details of all files that start with a through c and have 3 digits followed by .txt

file [a-c][0-9][0-9][0-9].txt

In the second example, we delete 2020 files that can start with any letter or number and the second to fifth character as 2020

rm ?2020*.txt

In the last example, to list all files that start with a or c and have exactly 3 characters after them and the third of those is a numeric, use

ls [ac]??[0-9].txt

The post Using wildcards in Linux appeared first on iExpertify.

]]>
How to remove non empty directory? https://www.iexpertify.com/linux/how-to-remove-non-empty-directory/ Fri, 09 Apr 2021 00:54:49 +0000 https://www.iexpertify.com/?p=12843 Reading Time: < 1 minute if you trying to delete a directory and all files under it, rmdir will fail with error message: The option is t remove using rm command with -rf option. r is for recursive and f is to force and ignore warnings and errors. There is no undo option, so be very careful. using the rm… Continue reading How to remove non empty directory?

The post How to remove non empty directory? appeared first on iExpertify.

]]>
Reading Time: < 1 minute

if you trying to delete a directory and all files under it, rmdir will fail with error message:

rmdir: failed to remove '<directory>': Directory not empty

The option is t remove using rm command with -rf option. r is for recursive and f is to force and ignore warnings and errors. There is no undo option, so be very careful.

rm -rf dirToDelete

using the rm -ir generates a message for each file or directory and deletion happens based on y or n that we can type in.

The post How to remove non empty directory? appeared first on iExpertify.

]]>
Simple Linux commands https://www.iexpertify.com/linux/simple-linux-commands/ Thu, 08 Apr 2021 12:45:44 +0000 https://www.iexpertify.com/?p=12839 Reading Time: 3 minutes These are a list of the most commonly used linux commands Command Description ls It is a list command and will display the directories and files visible under the present working directory ls -R Goes a step further to display or list files in sub-directories of the present working directory ls -a The argument -a… Continue reading Simple Linux commands

The post Simple Linux commands appeared first on iExpertify.

]]>
Reading Time: 3 minutes

These are a list of the most commonly used linux commands

CommandDescription
lsIt is a list command and will display the directories and files visible under the present working directory
ls -RGoes a step further to display or list files in sub-directories of the present working directory
ls -aThe argument -a in this list command helps list all the hidden files in the present working directory
ls -alThe argument -al in this list command gives a detailed list of the displayed files and directories with extra information such as size, permission, owner, etc.
cd or cd ~Takes you to the Home directory of your Linux operating system
cd ..navigates you backwards to the parent directory of the current directory you are under.
cdcombine it with a target directory under the present working directory to navigate to it e.g cd Downloads
cd /Takes you to the root directory of your Linux operating system
cat > filenameIt will create a file called filename
cat filenameIt will display the contents of a file called filename
cat file_1 file_2 > file_3Joins the content of file_1 and file_2 and copies the result to a newly created file_3
mv file_random “defined file path”It will move the file called file_random to the target file path or destination you will define.
mv file_name new_filenameIt will rename the file called file_name to a new file name called new_filename
sudoA command used by sudoer users to execute privileged commands applicable to a root user or superuser.
rm filenameIt will delete a file called filename
manUse it with a Linux command you do not understand to get help on how to use it. E.g man sudo
historyIt will display a list of the previous Linux terminal commands you have executed under that specific session.
clearIt will clear your command-line interface if you feel it is too crowded.
mkdir directory_nameit will create a director called directory_name
rmdir my_directoryIt will delete a directory called my_directory
mvYou can use it to rename a directory or a file
pr -xIt will divide or split a file to x defined columns.
pr -hUse it to add a header to a target file.
pr -nUses Line numbers to denote a target user file.
lp -nc, lpr cIt is a printing function and in this case it will print c copies of a target file.
lp -d lp -PHelps you identify the name of the printer you are using.
apt or apt-getA Debian distro package command for installing system updates and package applications
mail -s ‘mail_subject’ -c ‘cc-mail_address’ -b ‘bcc-mail_address’ ‘to-mail_address’Use this command to send an email from the terminal.
mail -s “mail_subject” to-mail_address < attachment_filenameUse this command to also send an email from the terminal but this time with an attachment.

The post Simple Linux commands appeared first on iExpertify.

]]>