Linux Commands Flashcards

1
Q

How check how much memory available and used on server?

A
  • free (free - m)
  • cat /proc/meminfo
  • vmstat
  • top
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How find kernel version?

A
  • cat /proc/version
  • uname -r
  • hostnamectl | grep Kernel
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How find Linux distribution?

A
  • cat /etc/os-release
  • lsb_release -a
  • hostnamectl
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How find CPU(s) on motherboard?

A
  • cat /proc/cpuinfo

- lscpu

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How find the number of CPU cores?

A
  • cat /proc/cpuinfo | grep ‘core id’
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How list devices on PCIe bus?

A
  • lspci
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How list installed packages?

A
  • “yum list installed”

- “dnf list installed”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How display kernel modules?

A
  • lsmod
  • /proc/modules
  • dnf module list (all modules)
  • dnf module list –enabled (list of enabled modules)
  • dnf module list –disabled
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you load/unload a kernel module?

A
  • modprobe can load/unload a “loadable” module
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How find more info about a module?

A
  • modinfo (find driver name from lsmod)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Where are kernel modules stored?

A

/lib/modules/$(uname -r)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How mount device?

A

I uselsblkto get my mount points, which is different frommountFor melsblkis easier to read thanmount

Make sure that you have a directory created before you go to mount your device.

sudo mkdir /{your directory name here} sudo mount /dev/{specific device id} /{your directory name here that is already created}

You should be good to go, however check security permissions on that new directory to make sure it’s what you want

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How view/modify disk partitions?

A
  • fdisk
  • parted
  • df (will show partitions even if not real drives - ram drive)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is fstab?

A
  • file system table. Each line in the file describes a filesystem, and contain fields used to provide information about its mountpoint, the options which should be used when mounting it etc.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How run linux job in background? How bring it back to foreground?

A

For running a process in background use “&” in command line. For bringing it back in foreground use command “fg jobid” and for getting job id you use command jobs, for killing that process find PID and use kill -9 PID command. This is indeed a good Unix Command interview questions because many of programmer not familiar with background process in UNIX. See NOHUP for keeping process running after logout.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How see previously used commands from command line?

A
  • “history” command
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How find how much space left on drives?

A
  • “df”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a zombie process?

A

When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the child’s exit status. To be able to get this information, the parent calls ‘wait()’; In the interval between the child terminating and the parent calling ‘wait()’, the child is said to be a ‘zombie’ (If you do ‘ps’, the child will have a ‘Z’ in its status field to indicate this.)
Zombie : The process is dead but have not been removed from the process table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How find files?

A

To find files that match a specific pattern, use the -name argument. You can use filename metacharacters (such as * ), but you should either put an escape character ( \ ) in front of each of them or enclose them in quotes.

For example, if we want to find all the files that start with “pro” in the Documents directory, we would use the cd Documents/ command to change to the Documents directory, and then type the following command:

find . -name pro*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How check of process is listening on a remote server and port

A
  • telnet
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How keep process running in background after user logs out?

A

nohup is a special command which is used to run process in background, but it is slightly different than & which is normally used for putting a process in background. An UNIX process started with nohup will not stop even if the user who has stared log off from system. While background process started with & will stop as soon as user logoff.

$ nohup command-name &
$ exit
or

$ nohup /path/to/command-name arg1 arg2 > myoutput.log &
$ exit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is ephemeral port?

A

An ephemeral port is a short-lived transport protocol port for Internet Protocol (IP) communications. Ephemeral ports are allocated automatically from a predefined range by the IP stack software. An ephemeral port is typically used by the Transmission Control Protocol (TCP), User Datagram Protocol (UDP), or the Stream Control Transmission Protocol (SCTP) as the port assignment for the client end of a client–server communication to a particular port (usually a well-known port) on a server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How see update of command/process output?

A
  • use ‘watch’
    for example to watch drive space every 5 secs, use:
    “watch -n 5 df -h”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How replace words in file/data?

A
  • use sed (stream editor):

“sed s/Unix/UNIX/g fileName”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How find how long server has been running?

A

-“uptime”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

If you have IP address, how find hostname?

A
  • nslookup ‘ hostname’

- nslookup ‘ip_address’

27
Q

How set up static/DHCP IP address?

A

Use ifconfig -a to find the network interface (i.e. enp0s3)

Edit /etc/sysconfig/network-scripts/ifcfg- (like: enp0s3)

===STATIC IP====

DEVICE=enp3s0
ONBOOT=yes
IPADDR=192.168.1.10
NETMASK=255.255.255.0
GATEWAY=192.168.1.1

Can restart just the interface by doing:
ifdown enp0s3
ifup enp0s3
(could be problem if connected remotely)

(longer example below)

HWADDR=08:00:27:98:06:76
TYPE=Ethernet
# Static IP Address #
BOOTPROTO=none
# Server IP #
IPADDR=192.168.1.10
# Netmask #
NETMASK=255.255.255.0
# Default Gateway IP #
GATEWAY=192.168.1.1
# DNS Servers #
DNS1=192.168.1.1
DNS2=8.8.8.8
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
# Disable ipv6 #
IPV6INIT=no
# Device Name #
NAME=enp0s3
DEVICE=enp0s3
# Optional – This is system specific and can be created using ‘uuidgen enp0s3’ command #
UUID=02d4a47b-3dbe-4e0b-ae4b-841a8c58e807
# Activate on Boot #
ONBOOT=yes
# Default Domain Search #
DOMAIN=itzgeek.local

systemctl restart network

====DHCP IP====
Edit /etc/sysconfig/network-scripts/ifcfg-eth0:

short answer is to modify file:
DEVICE=enp3s0
ONBOOT=yes
DHCP=yes

(longer version):

DEVICE="eth0"
ONBOOT=yes
NETBOOT=yes
UUID="41171a6f-bce1-44de-8a6e-cf5e782f8bd6"
IPV6INIT=yes
BOOTPROTO=dhcp
HWADDR="00:08:a2:0a:ba:b8"
TYPE=Ethernet
NAME="eth0"
28
Q

Why LVM is required ?

A

LVM stands for Logical Volume Manager , to resize filesystem’s size online we required LVM partition in Linux. Size of LVM partition can be extended and reduced using the lvextend & lvreduce commands respectively.

29
Q

How To check Memory stats and CPU stats?

A

Using ‘free’ & ‘vmstat’ command we can display the physical and virtual memory statistics respectively.With the help of ‘sar’ command we see the CPU utilization & other stats.

30
Q

What does Sar provides and at which location Sar logs are stored ?

A

Sar Collect, report, or save system activity information. The default version of the sar command (CPU utilization report) might be one of the first facilities the user runs to begin system activity investigation, because it monitors major system resources. If CPU utilization is near 100 percent (user + nice + system), the workload sampled is CPU-bound.

By default log files of Sar command is located at /var/log/sa/sadd file, where the dd parameter indicates the current day.

31
Q

How to increase the size of LVM partition ?

A

for XFS, can use “xfs_growfs” command, but more complicated than that.

Below are the Logical Steps :
– Use the lvextend command (lvextend -L +100M /dev/ , in this example we are extending the size by 100MB.
– resize2fs /dev/
– check the size of partition using ‘df -h’ command

32
Q

How to reduce or shrink the size of LVM partition ?

A

Below are the logical Steps to reduce size of LVM partition :

  • Umount the filesystem using umount command,
  • use resize2fs command , e.g resiz2fs /dev/mapper/myvg-mylv 10G
  • Now use the lvreduce command , e.g lvreduce -L 10G /dev/mapper/myvg-mylv

Above Command will shrink the size & will make the filesystem size 10GB.

33
Q

How to create partition from the raw disk ?

A

Using fdisk utility we can create partitions from the raw disk.Below are the steps to create partition from the raw dsik :
– fdisk /dev/hd* (IDE) or /dev/sd* (SCSI)
– Type n to create a new partition
– After creating partition , type w command to write the changes to the partition table.

34
Q

Where the kernel modules are located ?

A

The ‘/lib/modules/kernel-version/’ directory stores all kernel modules or compiled drivers in Linux operating system. Also with ‘lsmod’ command we can see all the installed kernel modules.

35
Q

What is umask ?

A

umask stands for ‘User file creation mask’, which determines the settings of a mask that controls which file permissions are set for files and directories when they are created.

36
Q

How to set the umask permanently for a user?

A

To set this value permanently for a user, it has to be put in the appropriate profile file which depends on the default shell of the user.

37
Q

How to share a directory using nfs ?

A

To share a directory using nfs , first edit the configuration file ‘/etc/exportfs’ , add a entry like
‘/ (Options)’ and then restart the nfs service.

38
Q

How to check and mount nfs share ?

A

Using ‘showmount’ command we can see what directories are shared via nfs e.g ‘showmount -e ’.Using mount command we can mount the nfs share on linux machine.

39
Q

What are the default ports used for SMTP,DNS,FTP,DHCP,SSH and squid ?

A
SMTP          25
HTTP          80
HTTPS        443
DNS            53
FTP             20 (data transfer) , 21 ( Signaling/Connection established)
telnet         23
TFTP          69
IMAP          143
POP3          110
DHCP         67/UDP(dhcp server) , 68/UDP(dhcp client)
SSH            22
Squid         3128
40
Q

What is Network Bonding ?

A

Network bonding is the aggregation of multiple Lan cards into a single bonded interface to provide fault tolerance and high performance. Network bonding is also known as NIC Teaming.

41
Q

What are the different modes of Network bonding in Linux ?

A

Below are list of modes used in Network Bonding :

balance-rr or 0 – round-robin mode for fault tolerance and load balancing.
active-backup or 1 – Sets active-backup mode for fault tolerance.
balance-xor or 2 – Sets an XOR (exclusive-or) mode for fault tolerance and load balancing.
broadcast or 3 – Sets a broadcast mode for fault tolerance. All transmissions are sent on all slave interfaces.
802.3ad or 4 – Sets an IEEE 802.3ad dynamic link aggregation mode. Creates aggregation groups that share the same speed & duplex settings.
balance-tlb or 5 – Sets a Transmit Load Balancing (TLB) mode for fault tolerance & load balancing.
balance-alb or 6 – Sets an Active Load Balancing (ALB) mode for fault tolerance & load balancing.

42
Q

How to check and verify the status the bond interface.

A

Using the command ‘cat /proc/net/bonding/bond0’ , we can check which mode is enabled and what lan cards are used in this bond. In this example we have one only one bond interface but we can have multiple bond interface like bond1,bond2 and so on.

43
Q

How to check default route and routing table ?

A

Using the Commands ‘netstat -nr’ and ‘route -n’ we can see the default route and routing tables.

44
Q

How to check which ports are listening in my Linux Server ?

A

Use the Command ‘netstat –listen’ and ‘lsof -i’

45
Q

What is load average in Linux ?

A

Load Average is defined as the average sum of the number of process waiting in the run queue and number of process currently executing over the period of 1,5 and 15 minutes. Using the ‘top’ and ‘uptime’ command we find the load average of a Linux sever.

46
Q

What is Linux and also explain the basic components of Linux?

A

Linux operating system is consist of 3 components which are as below:

Kernel: Linux is a monolithic kernel that is free and open source software that is responsible for managing hardware resources for the users.
System Library: System Library plays a vital role because application programs access Kernels feature using system library.
System Utility: System Utility performs specific and individual level tasks.

47
Q

What is the maximum length for a filename allowed in Linux?

A

Any filename can have a most extreme of 255 characters. This farthest point does exclude the pathname, so accordingly the whole pathname and filename could very much surpass 255 characters.

The interviewer generally asks this linux interview question and confuse the candidate by further asking if the mentioned length includes pathname. So, get prepared with the complete answer and explain it before the interviewer asks you more.

48
Q

What is the similarity and difference between cron and anacron? Which one would you prefer to use?

A

Cron and Anacron are used to schedule the tasks in cron jobs. Both of these are the daemons that are used to schedule the execution of commands or tasks as per the information provided by the user.

Differences between cron and anacron:

One of the main difference between cron and anacron jobs is that cron works on the system that are running continuously that means it is designed for the system that is running24*7. While anacron is used for the systems that are not running continuously.
Other difference between the two is cron jobs can run every minute, but anacron jobs can be run only once a day.
Any normal user can do the scheduling of cron jobs, but the scheduling of anacron jobs can be done by the superuser only.
Cron should be used when you need to execute the job at a specific time as per the given time in cron, but anacron should be used in when there is no any restriction for the timing and can be executed at any time.
If we think about which one is ideal for servers or desktops, then cron should be used for servers while anacron should be used for desktops or laptops.

49
Q

What is the issue behind getting an error “filesystem is full” while there is space available when you check it through “df” command? How will you rectify this problem?

A

When all the inodes are consumed then even though you have free space, you will get the error that filesystem is full. So, to check whether there is space available, we have to use the command df –i. Sometimes, it may happen file system or storage unit contains the substantial number of small files, and each of the files takes 128 bytes of the inode structure then inode structure fills up, and we will not be able to copy any more file to the disk. So, to rectify the problem, you need to free the space in inode storage, and you will be able to save more files.

50
Q

Where is password file located in Linux and how can you improve the security of password file?

A

This is an important question that is generally asked by the interviewers. User information along with the passwords in Linux is stored in/etc/passwd that is a compatible format. But this file is used to get the user information by several tools. Here, security is at risk. So, we have to make it secured.

To improve the security of the password file, instead of using a compatible format we can use shadow password format. So, in shadow password format, the password will be stored as single “x” character which is not the same file (/etc/passwd). This information is stored in another file instead with a file name /etc/shadow. So, to enhance the security, the file is made word readable and also, this file is readable only by the root user. Thus security risks are overcome to a great extent by using the shadow password format.

51
Q

What do you mean by an ext3 file system?

A

This is one of the top linux interview questions asked in the linux interview. It can be answered in the following manner. Ext3 file system is an upgraded version of ext2 and it also supports journaling. When an unclean shutdown is performed ext2 file system performs a check on the machine for errors which is a long process but it is not so in case of the ext3 file system.

In case of a hardware failure, an ext3 consistency check will occur without any pause. The time of the recovery of the file system is independent of the number of files. The time is dependent on the size of the journal which only takes a second which depends on the speed of the hardware.

52
Q

What are soft links? Describe some of the features of soft links.

A

Soft Links or Symbolic Link or Symlink are special files which are used as a reference for another directory. Some features of softlinks are:

They have a different INODE number with respect to source files or original files.
If in case the original file is deleted then a soft link of that file is useless.
We cannot update a soft link.
Soft links are used to create links between directories.
Soft links are independent of file system boundaries.

53
Q

Explain INODE in Linux.

A

INODE is a structure which acts as an identity for all files and objects. Type a command in the shell “ls -i”. The numbers which are displayed at the adjacent of files and folders, these are INODE numbers which are assigned to each file that contains information about the file. The system uses this number to identify the file. Information like the size of the file, when the file was modified etc is contained in an INODE number.

The questions based on INODE is the most common linux interview question you may come across in your linux interview. So, read well and get enough knowledge even if you are not familiar with it and get ready with the answer.

54
Q

How do you create a new user account and set the password for a user from a shell prompt in Linux?

A

To create a new user account from a shell prompt follow the below steps:

Log in as root user if you are not logged in as root using su – command.
Enter the root user password
The useradd command is used to create a new user in Linux. So, type command useradd and give the username you want to create as given below:
Useradd smith

To set the password of the user smith type the command: passwd smith
It will prompt for the new password. Enter the new password for user smith.
It will ask to retype the password. So, retype the same password and password is set for the user.

55
Q

Explain all the fields in the/etc/passwd file?

A

/etc/passwd file contains the useful information for all the system users who log in. We have many fields in /etc/passwd file such as username, password, user ID, group ID, comment or user ID info, home directory, command /shell, etc. So, this file contains sensitive information regarding all the user accounts. There is a single line per user in this file. Colon (:) separates the fields in /etc/passwd. Below is the explanation of the fields.

Username: First field is the username that contains the username which is 1 to 32 length characters.
Password: This field does not show the actual password as the password is encrypted. Here, x character shows that password is encrypted that is located in /etc/shadow file.
User ID (UID): All the users created in Linux is given a user ID whenever the user is created. UID 0 is fixed and reserved for the root user.
Group ID (GID): This field specifies the name of the group to which the user belongs. The group information is also stored in a file /etc/group.
User ID Info: Here you can add comments and you can add any extra information related to the users like full name, contact number, etc.
Home directory: This field provides the path where the user is directed after the login. For example, /home/smith.
Command/shell: This field provides the path of a command/shell and denotes that user has access to this shell i.e. /bin/bash.

56
Q

How can an administrator know whether a user account is locked or not?

A

To check if the user account is locked or not just run this command in the shell:

passwd –S

Or search for the grep username in the location /etc/shadow file and it will show a symbol ‘!’ prefix to the encrypted field in the password box.

To just unlock the password type this command:

passwd –u

If there is a double exclamation mark then run this command two times:

usermod –U

57
Q

What do you mean by SELinux?

A

SELinux is the abbreviation for Security Enhanced Linux. The access controls for the users can be controlled using SELinux. For example, the users can be stopped from running the scripts and accessing their own home directories. SELinux has the capability to support the access control and security policies. It basically operates on three different modes:

Enforcing –to enforce its policies.
Permissive –Polices want to apply but will be locked in case of violation.
Disabled –SELinux will stay in disabled mode.
To check the status of SELinux, just type: #getenfore OR sestatus

58
Q

Mention the run levels in Linux and steps to edit them.

A

systemctl get-default

initd Run levels are identified by numbers in Linux. The run levels determine what are the services that are currently in operation. There are seven different run levels in Linux:

0-Halt -Shuts down system
1-Single-User Mode - Does not configure network interfaces, start daemons, or allow non-root logins
2-Multi-User Mode - Does not configure network interfaces or start daemons.
3-Multi-User Mode with Networking - Starts the system normally.
4-Undefined - Not used/User-definable
5-X11 - As runlevel 3 + display manager(X)
6-Reboot - Reboots the system

To change the edit level /etc/inittlab and edit the initdefault entry.

systemd:

  • Run level 0 is matched by poweroff.target (and runlevel0.target is a symbolic link to poweroff.target).
  • Run level 1 is matched by rescue.target (and runlevel1.target is a symbolic link to rescue.target).
  • Run level 3 is emulated by multi-user.target (and runlevel3.target is a symbolic link to multi-user.target).
  • Run level 5 is emulated by graphical.target (and runlevel5.target is a symbolic link to graphical.target).
  • Run level 6 is emulated by reboot.target (and runlevel6.target is a symbolic link to reboot.target).
  • Emergency is matched by emergency.target.

How to View Current target (run level) in Systemd
When the system boots, by default systemd activates the default.target unit. It’s main work is to activate services and other units by pulling them in via dependencies.

To view the default target, type the command below.

To set the default target, run the command below.

systemctl set-default multi-user.target

How to Change the target (runlevel) in Systemd
While the system is running, you can switch the target (run level), meaning only services as well as units defined under that target will now run on the system.

To switch to runlevel 3, run the following command.

systemctl isolate multi-user.target

To change the system to runlevel 5, type the command below.

systemctl isolate graphical.target

59
Q

How can we create a local Yum repository in the location /media with the use of mounted Linux ISO image?

A

To create the local yum repository you have to create the files ending with extension .repo in the location /etc/yum.repos.d

Syntax: [root@localhost yum.repos.d]# cat local.repo

[local]

name=RHEL6.5

baseurl=file:///media

enabled=1

gpgcheck=1

gpgkey=file:///media/RPM-GPG-KEY-redhat-release

60
Q

Explain system calls used for process management?

A

There are some system calls used in Linux for process management. These are as follows:

Fork(): It is used to create a new process

Exec(): It is used to execute a new process

Wait(): It is used to make the process to wait

Exit(): It is used to exit or terminate the process

Getpid(): It is used to find the unique process ID

Getppid(): It is used to check the parent process ID

Nice(): It is used to bias the currently running process property

61
Q

What is AWK?

A

Awk is a scripting language used for manipulating data and generating reports.The awk command programming language requires no compiling, and allows the user to use variables, numeric functions, string functions, and logical operators.

Awk is a utility that enables a programmer to write tiny but effective programs in the form of statements that define text patterns that are to be searched for in each line of a document and the action that is to be taken when a match is found within a line. Awk is mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the specified patterns and then performs the associated actions.

Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.

WHAT CAN WE DO WITH AWK ?

  1. AWK Operations:
    (a) Scans a file line by line
    (b) Splits each input line into fields
    (c) Compares input line/fields to pattern
    (d) Performs action(s) on matched lines
  2. Useful For:
    (a) Transform data files
    (b) Produce formatted reports
  3. Programming Constructs:
    (a) Format output lines
    (b) Arithmetic and string operations
    (c) Conditionals and loops

Example:
Consider the following text file as the input file for all cases below.

$cat > employee.txt 
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000 
1. Default behavior of Awk : By default Awk prints every line of data from the specified file.

$ awk ‘{print}’ employee.txt
Output:

ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000 
In the above example, no pattern is given. So the actions are applicable to all the lines. Action print without any argument prints the whole line by default, so it prints all the lines of the file without failure.
  1. Print the lines which matches with the given pattern.

$ awk ‘/manager/ {print}’ employee.txt
Output:

ajay manager account 45000
varun manager sales 50000
amit manager account 47000
In the above example, the awk command prints all the line which matches with the ‘manager’.

  1. Splitting a Line Into Fields : For each record i.e line, the awk command splits the record delimited by whitespace character by default and stores it in the $n variables. If the line has 4 words, it will be stored in $1, $2, $3 and $4 respectively. Also, $0 represents the whole line.

$ awk ‘{print $1,$4}’ employee.txt
Output:

ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000 
In the above example, $1 and $4 represents Name and Salary fields respectively.

Built In Variables In Awk

Awk’s built-in variables include the field variables—$1, $2, $3, and so on ($0 is the entire line) — that break a line of text into individual words or pieces called fields.

NR: NR command keeps a current count of the number of input records. Remember that records are usually lines. Awk command performs the pattern/action statements once for each record in a file.

NF: NF command keeps a count of the number of fields within the current input record.

FS: FS command contains the field separator character which is used to divide fields on the input line. The default is “white space”, meaning space and tab characters. FS can be reassigned to another character (typically in BEGIN) to change the field separator.

RS: RS command stores the current record separator character. Since, by default, an input line is the input record, the default record separator character is a newline.

OFS: OFS command stores the output field separator, which separates the fields when Awk prints them. The default is a blank space. Whenever print has several parameters separated with commas, it will print the value of OFS in between each parameter.

ORS: ORS command stores the output record separator, which separates the output lines when Awk prints them. The default is a newline character. print automatically outputs the contents of ORS at the end of whatever it is given to print.

Examples:

Use of NR built-in variables (Display Line Number)

$ awk ‘{print NR,$0}’ employee.txt
Output:

1 ajay manager account 45000
2 sunil clerk account 25000
3 varun manager sales 50000
4 amit manager account 47000
5 tarun peon sales 15000
6 deepak clerk sales 23000
7 sunil peon sales 13000
8 satvik director purchase 80000 
In the above example, the awk command with NR prints all the lines along with the line number.

Use of NF built-in variables (Display Last Field)

$ awk ‘{print $1,$NF}’ employee.txt
Output:

ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
deepak 23000
sunil 13000
satvik 80000 
In the above example $1 represents Name and $NF represents Salary. We can get the Salary using $NF , where $NF represents last field.

Another use of NR built-in variables (Display Line From 3 to 6)

$ awk ‘NR==3, NR==6 {print NR,$0}’ employee.txt
Output:

3 varun manager sales 50000
4 amit manager account 47000
5 tarun peon sales 15000
6 deepak clerk sales 23000 
More Examples

For the given text file:

$cat > geeksforgeeks.txt

A    B    C
Tarun    A12    1
Man    B6    2
Praveen    M42    3
1) To print the first item along with the row number(NR) separated with ” – “ from each line in geeksforgeeks.txt:

$ awk ‘{print NR “- “ $1 }’ geeksforgeeks.txt
1 - Tarun
2 – Manav
3 - Praveen
2) To return the second row/item from geeksforgeeks.txt:

$ awk '{print $2}' geeksforgeeks.txt
A12
B6
M42
3) To print any non empty line if present

$ awk ‘NF > 0’ geeksforgeeks.txt
0
4) To find the length of the longest line present in the file:

$ awk ‘{ if (length($0) > max) max = length($0) } END { print max }’ geeksforgeeks.txt
13
5) To count the lines in a file:

$ awk ‘END { print NR }’ geeksforgeeks.txt
3
6) Printing lines with more than 10 characters:

$ awk ‘length($0) > 10’ geeksforgeeks.txt
Tarun A12 1
Praveen M42 3
7) To find/check for any string in any column:

$ awk ‘{ if($3 == “B6”) print $0;}’ geeksforgeeks.txt
8) To print the squares of first numbers from 1 to n say 6:

$ awk 'BEGIN { for(i=1;i<=6;i++) print "square of", i, "is",i*i; }'
square of 1 is 1
square of 2 is 4
square of 3 is 9
square of 4 is 16
square of 5 is 25
square of 6 is 36
This article is contributed by Anshika Goyal and Praveen Negi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

62
Q

I was wondering what “loop” mean in this usage of mount:

“mount -t iso9660 -o loop matlab.iso /media/cdrom0”

A

A “loop” device in Linux is an abstraction that lets you treat a file like a block device. It’s specifically meant for a use like your example, where you can mount a file containing a CD image and interact with the filesystem in it as if it were burned to a CD and placed in your drive.

63
Q

can anyone explain what exactly vmlinuz does?

A

vmlinuz is the compressed image of the kernel. It gets uncompressed, loaded into memory, and executed at boot