Breaking

LFCS Exam Guide

 -----------------du------------------------------------------------

$ sudo du --max-depth=1 -hx /

$ sudo du -sh /


-----------------Ulimit------------------------------------------------

Ulimit -a

$ ulimit -H -n

$ ulimit -S -n

$ ulimit -n 1600

/etc/security/limits.conf  then reboot.

@<group>        hard    nproc            <value>

<user>          soft    nproc            <value>

## Example hard limit for max opened files

marin        hard      nofile     4096

# vi /root/.bashrc                    limit of processes for the super-user root to be unlimited

            ulimit -u unlimited

$ ulimit -u unlimited


-----------------nice------------------------------------------------

$ nice -n 5 command [ARGS]

$ nice -5 command [ARGS]

$ nice

$ nice cat &

$ ps -l

$ renice +5 -p 20003


-----------------Opened files------------------------------------------------

$ lsof /dev/null
$ lsof -u tecmint
$ lsof

-----------------grep------------------------------------------------

grep '^hai' 1.txt       
grep 'running$' 1.txt

grep -E 'hai|running' 1.txt
grep  'hai\|running' 1.txt
egrep 'hai|running' 1.txt

grep '^hai.*running$' 1.txt

------------------dpkg-----------------------------------------------

$ dpkg -l        List all packages installed:

$ dpkg -L wget    List files installed in the wget package:

$ dpkg -s wget    Show information about an installed package:

$ dpkg -I webfs_1.21+ds1-8_amd64.deb Show information about a package file:

$ dpkg -c webfs_1.21+ds1-8_amd64.deb List files in a package file:

$ dpkg -S /etc/init/networking.conf Show what package owns /etc/init/networking.conf:

$ dpkg -V package Verify the installed package's integrity:

$ sudo dpkg -i foobar.deb Installing/Upgrading

$ sudo dpkg -r package remove all of an installed package except for its configuration files

$ sudo dpkg -P package remove all of an installed package, including its configuration files


------------------apt-----------------------------------------------

$ sudo apt-get update

$ sudo apt-get upgrade

$ sudo apt-get -u upgrade

$ apt-cache search "kernel"

$ apt-cache search -n "kernel"

$ apt-cache pkgnames "kernel"

$ sudo apt-get install apache2-dev

$ apt-cache search bash

$ apt-cache search -n bash

$ apt-cache show bash basic information about the apache2 package

$ apt-cache showpkg apache2 detailed information about the apache2 package

$ apt-cache depends bash Lists all dependent packages for apache2:

$ apt-cache rdepends bash

$ sudo apt-get remove [package] remove a package from the system (this does not remove the configuration files)

$ sudo apt-get --purge remove [package] remove a package and its configuration files from a system


 -------------------Crontab------------------------------------------------------------------------------------------

 */1 * * * * pkill "scan_filesystem" > /root/exam/output.log 2>&1

 

  0 0 1 1 *           Run once a year at midnight on January 1

  0 0 1 * *           Run once a month at midnight on the first day of the month

  0 0 * * 0           Run once a week at midnight on Sunday morning

  0 0 * * *           Run once a day at midnight

  0 * * * *           Run once an hour at the beginning of the hour

  @reboot           Run at startup (of the cron daemon)

  10 16 * * *       runs a command at 4:10 PM

  0 2 * * 6           runs a command at 2:00 AM on Saturday

  0 0 1 1 0           runs at midnight on New Years Day (January 1st)

  0 * * * *           runs every hour

  */15 * * * *      runs every 15 minutes

  */30 * * * *      runs every 30 minutes

  */10 * * * *      runs every 10 minutes

  0 17-18 20 * * At minute 0 past every hour from 17 through 18 on day-of-month 20


--------------------MBR-Disk---------------------------------------------

blkid

lsblk

$ dd if=/dev/sda of=mbrbackup bs=512 count=1 backup the MBR (along with the partition table)

$ sudo dd if=mbrbackup of=/dev/sda bs=512 count=1 Restore MBR

$ sudo fdisk /dev/sdb fdisk

$ sudo partprobe -s

fsck /dev/sda The system will not use the new partition table until you reboot. However, you can


--------------file full of zeros 1 GB---------------------------------------------------

$ dd if=/dev/zero of=imagefile bs=1M count=1024 Create a file full of zeros 1 GB in length

$ mkfs.ext4 imagefile

$ mkdir mntpoint

$ sudo mount -o loop imagefile mntpoint

$ sudo umount mntpoint


---------------fdisk--------------------------------------------------

$ sudo fdisk -C 130 imagefile

m

Command (m for help): n

Command (m for help): p

Command (m for help): w

$ sudo mkfs -t ext4 /dev/sda10

$ sudo mkfs.ext4 /dev/sda10

$ mkfs.ext4 /dev/sda1 -L ROOT                Label while formating

$ sudo fsck -t ext4 /dev/sda10

$ sudo fsck.ext4 /dev/sda10

$ sudo fsck /dev/sda10

$ mount -t ext /dev/sdb4 /home

$ umount /home

$ umount /dev/sda3

$ sudo mount -t nfs myserver.com:/shdir /mnt/shdir​

myserver.com:/shdir /mnt/shdir nfs rsize=8192,wsize=8192,timeo=14,intr 0 0 fstab

$ mount -a


---------------Attributes--------------------------------------------------

$ lsattr filename

$ chattr [+|-|=mode] filename

i: Immutable

a: Append-only

d: No-dump

A: No atime update


----------------Quota-------------------------------------------------

sudo apt update

sudo apt install quota

sudo apt install linux-image-extra-virtual

# vim /etc/fstab

        /dev/VolGroup00/LogVol02 /home     ext3    defaults,usrquota,grpquota  1 2 

$ sudo mount -o remount,usrquota,grpquota /

umount /mount-point

mount /file-system /mount-point

mount /dev/vdb1 /work

# quotacheck -cug /home

# quotacheck -avug

# edquota username

# quota username

# edquota -g devel

# quota -g devel

$ sudo edquota -u user        Configure Quotas for a Single User

$ sudo quota -vs user        check the new user quota limit

# quotaoff -vaug

# quotaon -vaug

# quotaon -vug /home

# repquota /home

# repquota -a        generate report


-------------LVM----------------------------------------------------

# fdisk -cu /dev/sda

n

p

t

1

8e

w

$ partprobe -s

# pvs

# pvcreate /dev/sda1 /dev/sdb1 /dev/sdc1

# pvs

# vgs

# vgcreate tech_add_vg /dev/sda1 /dev/sdb1 /dev/sdc1

# vgs

# vgdisplay tech_add_vg

# lvs

# lvcreate -L 18G -n tech_documents tech_add_vg

# lvs

# mkfs.ext4 /dev/tech_add_vg/tech_documents

# mount /dev/tech_add_vg/tech_documents /mnt/tech_documents/

# df -h

# cat /etc/mtab

# vim /etc/fstab

        /dev/mapper/tech_add_vg-tech_documents    /mnt/techt_documents  ext4    defaults 0 0

# mount -av


-----------SWAP------------------------------------------------------

swapoff -v /dev/VolGroup00/LogVol01

$ swapoff -a

# lvextend -L +2G /dev/mapper/fedora_studentvm1-swap

mkswap /dev/VolGroup00/LogVol01

swapon -va  or  sudo swapon /swapfile

$ swapon -a

vim /etc/

/dev/sdaY         swap        swap    defaults        0 0

cat /proc/swaps

free


-------------RAID-mdadm----------------------------------------------------

$ sudo apt-get update -y

$ sudo apt-get install -y mdadm

$ sudo fdisk /dev/sdb

$ sudo fdisk /dev/sdc

$ sudo mdadm --create /dev/md0 --level=1 --raid-disks=2 /dev/sdbX /dev/sdcX

$ sudo mkfs.ext4 /dev/md0

$ sudo bash -c "mdadm --detail --scan >> /etc/mdadm.conf"

$ sudo mkdir /myraid

$ sudo mount /dev/md0 /myraid

$ vim /etc/fstab

/dev/md0 /myraid ext4 defaults 0 2

$ cat /proc/mdstat

$ sudo mdadm -S /dev/md0 to stop the RAID device.

$ sudo systemctl start mdmonitor

$ sudo systemctl enable mdmonitor

$ sudo mdadm --create /dev/md0 -l 5 -n3 -x 1 /dev/sda8 /dev/sda9 /dev/sda10 /dev/sdb2 To create a hot spare when creating the RAID array


----------------------RAID-mdadm-------------------------------------------

$ sudo fdisk /dev/sda

partprobe

$ sudo mdadm -C /dev/md0 --level=1 --raid-disks=2 /dev/sdaX /dev/sdaY

$ sudo mdadm --create --verbose /dev/md0 --level=5 --raid-devices=3 /dev/sda /dev/sdb /dev/sdc

$ sudo mkfs.ext4 /dev/md0

$ sudo mkdir /myraid

$ sudo mount /dev/md0 /myraid

$ vim /etc/fstab

        /dev/md0  /myraid    ext4    defaults

$ sudo bash -c "mdadm --detail --scan >> /etc/mdadm.conf"

$ cat /proc/mdstat

Add a new disk

# mdadm --manage /dev/md0 --add /dev/sdd1

# mdadm --detail /dev/md0

# mdadm --grow --raid-devices=3 /dev/md0

-----------cryptsetup-Encryption------------------------------------------------------

$ apt-get update

$ apt-get install cryptsetup

$ modprobe dm_crypt

$ sudo fdisk /dev/sda

$ sudo partprobe -s

$ sudo cryptsetup luksFormat /dev/sda4

$ sudo cryptsetup luksOpen /dev/sda4 secret-disk

$ vim /etc/crypttab

        secret-disk    /dev/sda4

$ sudo mkfs -t ext4 /dev/mapper/secret-disk

$ sudo mkdir -p /secret

$ vim /etc/fstab

        /dev/mapper/secret-disk    /secret    ext4    defaults

$ sudo mount /secret

$ sudo mount -a

reboot


----------------virsh-------------------------------------------------

virsh

https://ostechnix.com/manage-kvm-virtual-machines-with-virsh-program/

$ qemu-img convert -O vmdk myvm.qcow2 myvm.vmdk Convert format

$ grep -e vmx -e svm /proc/cpuinfo check that you have hardware virtualization available and enabled


$ sudo systemctl stop vmware

$ sudo systemctl disable vmware

$ sudo systemctl stop vboxdrv

$ sudo systemctl disable vboxdrv



$ sudo systemctl start libvirtd

$ sudo virt-manager

tc-install


$ sudo qemu-img create -f qcow2 /var/lib/libvirtd/myimg.qcow2 24M

$ sudo qemu-system-x86_64 -hda /var/lib/libvirtd/myimg.qcow2 \ -cdrom /teaching/LFCW/RESOURCES/LFS201/CorePlus-current.iso  -usbdevice tablet


----------------PAM-------------------------------------------------

/etc/pam.d


-----------------hostnamectl------------------------------------------------

$ hostname

$ sudo hostname lumpy

$ sudo hostnamectl set-hostname lumpy

$ hostnamectl


------------ip link-----------------------------------------------------

$ ip link show

$ ip -s link show eth0

$ sudo ip addr add 192.168.1.7 dev eth0

$ sudo ip link set eth0 down

$ sudo ip link set eth0 mtu 1480

$ sudo ip route add 172.16.1.0/24 via 192.168.1.5


--------------ifconfig---------------------------------------------------

$ ifconfig

$ ifconfig eth0

$ sudo ifconfig eth0 192.168.1.50

$ sudo ifconfig eth0 netmask 255.255.255.0

$ sudo ifconfig eth0 up

$ sudo ifconfig eth0 down

$ sudo ifconfig eth0 mtu 1480



$ sudo ip link set eth0 down   OR   $ sudo ifconfig eth0 down

/etc/sysconfig/network  OR  /etc/networking/interfaces

        iface eth0 inet static

        address noted from step1

        netmask noted from step1

        gateway noted from step1


$ sudo ip link set eth0 up   OR   $ sudo ifconfig eth0 up

$ sudo cp resolv.conf.keep /etc/resolv.conf

$ cat /etc/hosts

        192.168.1.180 mysystem.mydomain

        127.0.0.1 ad.doubleclick.net

$ wget http://winhelp2002.mvps.org/hosts.txt

$ sudo sh -c "cat hosts.txt >> /etc/hosts"

$ ping yourhostname

$ sudo reboot

$ ping hostname


--------------nmcli-add another ip---------------------------------------------------

$ sudo nmcli con obtain your current internet address and interface name

$ sudo nmcli con show "Auto Ethernet" | grep IP4.ADDRESS

$ nmcli con show 1c46bf37-2e4c-460d-8b20-421540f7d0e2

$ sudo nmcli con show "Auto Ethernet" | grep IP4.ADDRESS

$ sudo nmcli con modify "Auto Ethernet" +ipv4.addresses 172.16.2.140/24

$ sudo nmcli con up "Auto Ethernet"

$ sudo nmcli con modify  "Auto Ethernet" -ipv4.addresses 172.16.2.140/24

$ sudo nmcli con up "Auto Ethernet"


--------------nmcli-add another route---------------------------------------------------

$ route

$ ip route

$ sudo nmcli conn mod "Auto Ethernet" +ipv4.routes "192.168.100.0/24 172.16.2.1"

$ route

$ sudo nmcli conn up "Auto Ethernet"

$ route

$ sudo nmcli conn mod "Auto Ethernet" -ipv4.routes "192.168.100.0/24 172.16.2.1"

$ sudo nmcli conn up "Auto Ethernet"


----------------firewall-cmd-------------------------------------------------

$ sudo systemctl [enable/disable] firewalld

$ sudo systemctl [start/stop] firewalld

$ sudo systemctl status firewalld

$ sudo firewall-cmd --state

$ sudo firewall-cmd --get-default-zone Get the default zone:

$ sudo firewall-cmd --get-active-zones Obtain a list of zones currently being used:

$ sudo firewall-cmd --get-zones List all available zones:

$ sudo firewall-cmd --set-default-zone=trusted To change the default zone to trusted and then change it back!

$ sudo firewall-cmd --set-default-zone=public then change it back

$ sudo firewall-cmd --zone=internal --change-interface=eno1 To assign an interface temporarily to a particular zone:

$ sudo firewall-cmd --permanent --zone=internal --change-interface=eno1 To assign an interface to a particular zone permanently:

$ sudo firewall-cmd --get-zone-of-interface=eno1 To ascertain the zone associated with a particular interface:

$ sudo firewall-cmd --zone=public --list-all Finally, to get all details about a particular zone:

man firewalld-cmd


$ sudo firewall-cmd --zone=home --add-port=21/tcp

$ sudo firewall-cmd --zone=home --list-ports

$ grep " 21/tcp" /etc/services


$ which firewalld firewall-cmd

$ sudo apt-get install firewalld

$ tar xvf firewalld-0.3.13.tar.bz2

$ cd firewalld-0.3.13

$ ./configure

$ make

$ sudo make install

$ sudo make uninstall

$ firewall-cmd --help


$ sudo firewall-cmd  --zone=public --add-service=http Adding Services to a Zone --permanent

$ sudo firewall-cmd  --zone=public --add-service=https Adding Services to a Zone --permanent

$ sudo firewall-cmd --list-services --zone=public

$ sudo firewall-cmd --reload

$ sudo firewall-cmd --list-services --zone=public

--permanent


-------------------grub-run level----------------------------------------------

/etc/default

/etc/default/useradd

$ sudo shutdown -r now Reboot the system using shutdown

$ sudo shutdown -h now Power off the system usingshutdown


/etc/default/grub 

/etc/grub.d

$ sudo grub2-install /dev/sda


$ sudo systemctl start gdm

$ sudo systemctl start lightdm

$ sudo telinit 5

$ sudo service gdm restart

$ sudo service lightdm restart

# update-grub


----------tar------------------------------------------------------------------------------------

tar -cfvj archive.tar.bz2 file1 file2

tar -xfvj archive.tar.bz2

tar -cfvz archive.tar.gz file1 file2

tar -xfvz archive.tar.gz

tar -cvf archive.tar file1 file2

tar -xvf archive.tar


------------diff----------------------------------------------------------------------------------

$ cmp file1 file2

$ diff file1 file2

$ diff -q directory-1/ directory-2/


--------------vim--------------------------------------------------------------------------------

100G            Jump to line 100

dd                delete 

10G            Jump to line 10

p                Paste

ww            Save


--------------input-output-redirection---------------------------------------------------

$ cat music.mp3 > /dev/audio

Mail -s "Subject" to-address < Filename

$ myprogram 2>errorsfile

find . -name 'my*' 2>error.log

ls Documents ABC> dirlist 2>&1


-------------Links---------------------------------------------------------------------------------

$ ln topprocs.sh tp

$ find -type f -links +1

 ls -i                 Files that are hard-linked together share the same inode number

$ ln -s /bin/topprocs.sh topps.sh

unlink symlink_name


------------find------------------------------------------------------------------------------------------------------------

1. Searching for files and directories named gcc:

$ find /usr -name gcc

2. Searching only for directories named gcc:

$ find /usr -type d -name gcc

3. Searching only for regular files named gcc:

$ find /usr -type f -name gcc

4. To find and remove all files that end with .swp: 

$ find -name "*.swp" -exec rm {} \;

5. To find files based on time:

$ find / -ctime 3

6. To find files based on sizes:

$ find / -size 0

7. To find files greater than 10 MB in size and running a command on those files:

$ find / -size +10M -exec command {} \;

8. Find Files With 777 Permissions:

# find . -type f -perm /0777 -print

9. Find Executable Files:

find <dir> -executable -type f

find / -perm /a=x

10. find and delete all empty directories:

find /path/to/dir -empty -type d -delete

find /path/to/dir -empty -type f -delete

11. cp -p $(find /root/test5/ -type f -perm /6000) /root/test6/

12. # find /root/test5/ -type f -perm /u=s,g=s

13. $ find . -size 6M

14. $ find . -size +2G

15. $ find . -size -10k

16. # find . -size +10M -size -20M

17. find . \! -user foo -print

18. find /tmp/systemd-private-apache2/tmp/ -type f -name "magick-*" -mtime +1 -delete

19. find /root/exam/ -type f -name "*.txt" \! -user test1  -perm 0777  -exec  cp -r  {} /root/exam/test/  \;

20. Find the init.d directory, starting from /, and then create a symbolic link from within your home directory to this directory

student:/tmp> find / -type d -name init.d

student:/tmp> cd ~

student:/home/student> ln -s /etc/init.d .


--------user management--------------------------------------------------------------------------------------

0 - no permission

1 - execute

2 - read

4 - write


4777 = u+s suid

2777 = g+s sgid

1777 = +t  stickybit


ls -l /etc/skel/

adduser user

$ sudo useradd -m -d /home/bob1 bob1


usermod -a -G group user

chown -R user:group /file

chgrp group filename

chown USER FILE

getent group


groupadd group-name

sudo groupdel staff


# groups gp-name

# group

# gpasswd -d user group Remove a User from a Group in Linux

# groups user


cat /etc/shells

# usermod --shell /bin/bash user

# vi /etc/passwd

sudo useradd -s /usr/bin/zsh username


---------------ENV-Variable--------------------------------------------------------------------------------------------

export NAME=VALUE

export JAVA_HOME=/opt/openjdk11

echo $JAVA_HOME


sudo nano ~/.bashrc

export [VARIABLE_NAME]=[variable_value]

export APACHE_RUN_USER="www-data"

$ source .bashrc

 OR

export PATH=$PATH:/myNewDir


-------------Container--------------------------------------------------------------------------------------------------

$ docker rm $(docker ps -a -q)            Delete all un used containers

$ sudo apt-get install docker.io

sudo systemctl start docker

sudo systemctl status docker

$ sudo docker search apache Search for the httpd container

$ sudo docker pull docker.io/httpd Retrieve the container

$ sudo docker images List the installed containers

# docker tag httpd aby                     Change tag name

$ sudo  docker images --all List the components associated with the images

sudo docker run httpd Start the httpd dockercontainer

# docker run -d  httpd                    Start the httpd docker container in background

$ elinks http://172.17.0.2

sudo docker ps Stop the container anddockerservice and clean up

sudo docker stop b936b0afeb23 Stop the container anddockerservice and clean up

# docker rmi -f aby                            Remove container

sudo docker rmi -f docker.io/httpd If you do not need to reuse them you can clean up

sudo docker system prune -a Deleted Containers

sudo systemctl stop docker


--------------apache------------------------------------------------------------------------------------------------------

# apt-get install apache2

# /etc/init.d/apache2 start

# /etc/init.d/apache2 status

# /etc/init.d/apache2 restart

# vim /etc/apache2/sites-available/yourdomain.com.conf


        <virtualhost *:80="">  

        ServerAdmin webmaster@localhost  

        ServerName yourdomain.com  

        ServerAlias www.yourdomain.com  

        DocumentRoot /var/www/yourdomain.com  

        ErrorLog ${APACHE_LOG_DIR}/error.log  

        CustomLog ${APACHE_LOG_DIR}/access.log combined  

        </virtualhost>


$ sudo a2ensite yourdomain.com.conf

$ sudo a2dissite 000-default.conf

# mkdir /var/www/yourdomain.com

# vi /var/www/yourdomain.com/index.html

# sudo systemctl restart apache2

http://yourdomain.com


----------sysctl-------------------------------------------------------

$ sysctl -a List kernel parameters

$ ls -l /proc/sys/kernel/ Location

$ sudo sysctl net.ipv4.ip_forward=1 Change Value

sysctl net.ipv4.icmp_echo_ignore_all Paramater Info


----------lsmod-------------------------------------------------------

uname -r

lsmod lsmod to list the loaded modules

/lib/modules/$(uname -r)/modules.dep.

$ sudo insmod /lib/modules/$(uname -r)/kernel/drivers/net/ethernet/intel/e1000e.ko Directly load modules

$ modinfo e1000e modinfo to display information about a module

$ modprobe e1000e modprobe to load a module

$ modprobe -r e1000e modprobe -r to unload or remove a module

dmesg -w


-----------udev------------------------------------------------------

Create and implement a rule on your system that will create a symlink calledmyusbwhen aUSBdevice is plugged in

$ cat /etc/udev/rules.d/75-myusb.rules

        SUBSYSTEM=="usb", SYMLINK+="myusb"

Plug in a device

ls -lF /dev | grep myusb

umount /media/whatever

$ ls -lF /dev | grep myusb


----------Adding a New Startup Service with systemd-------------------------------------------------------

vim /etc/systemd/system/fake2.service

        [Unit]
        Description=fake2
        After=network.target
        [Service]
        ExecStart=/bin/sh -c '/bin/echo I am starting the fake2 service ; /bin/sleep 30'
        ExecStop=/bin/echo I am stopping the fake2 service
        [Install]
        WantedBy=multi-user.target

$ sudo systemctl start fake2.service
$ sudo systemctl status fake2.service
$ sudo systemctl stop fake2.service
$ sudo systemctl daemon-reload
$ sudo tail -f /var/log/messages
$ sudo tail -f /var/log/syslog

------------Password Age-----------------------------------------------------

# chage --lastday 0 ravi              Change password on next login
# passwd --expire ravi                Change password on next login
# chage -l ravi
# chage -M number-of-days username
# chage -m 0 -M 99999 -I -1 -E -1 username          No expire


Some Other Useful Information


--------------------Methods of bringing down the GUI:-----------------------------------------------------------

student:/tmp> sudo systemctl stop gdm

student:/tmp> sudo systemctl stop lightdm

student:/tmp> sudo telinit 3

      

Methods of bringing the GUI back up:

student:/tmp> sudo systemctl start gdm

student:/tmp> sudo systemctl start lightdm

student:/tmp> sudo telinit 5


-----------------reboot/halt/poweroff----------------------------------------------------------------------------------

reboot the system is to use the shutdown command.

The halt and poweroff commands issue shutdown -h to halt the system

reboot issues shutdown -r and causes the machine to reboot instead of just shutting down


When administering a multi-user system, you have the option of notifying all users prior to shutdown, as in:

$ sudo shutdown -h 10:00 "Shutting down for scheduled maintenance."


---------------Locating Applications----------------------------------------------------------------------------------

$ which diff

$ whereis diff


---------------Accessing Directories-----------------------------------------------------------------------------------

pwd Displays the present working directory

cd ~ or cd Change to your home directory (shortcut name is ~ (tilde))

cd .. Change to parent directory (..)

cd - Change to previous directory (- (minus))

cd / Changes your current directory to the root (/) directory (or path you supply)

ls List the contents of the present working directory

ls –a List all files, including hidden files and directories (those whose name start with . )

tree Displays a tree view of the filesystem

tree -d /  tree view


-----------Hard Links---------------------------------------------------------------------------------------------------

If you remove either file1 or file2 in the example, the inode object (and the remaining file name) will remain, which might be undesirable, as it may lead to subtle errors later if you recreate a file of that name.

$ ln file1 file2   Suppose that file1 already exists. A hard link, called file2, is created with the command

$ ls -li file1 file2

$ ls -li file1?


-------------Soft (Symbolic) Links------------------------------------------------------------------------------------

Soft (or Symbolic) links are created with the -s option, as in:

$ ln -s file1 file3

$ ls -li file1 file3


--------------Navigating the Directory History---------------------------------------------------------------------

The cd command remembers where you were last, and lets you get back there with cd -

For remembering more than just the last directory visited, use pushd to change the directory instead of cd; this pushes your starting directory onto a list. Using popd will then send you back to those directories, walking in reverse order (the most recent directory will be the first one retrieved with popd). The list of directories is displayed with the dirs command.

cd /tmp/dir1

pushd .  Push current directoy to stack

cd /tmp/dir2

pushd .  Push current directoy to stack

dirs   To view directories in stack

popd   To pop the top-most directory from the stack

pwd

popd   To pop the top-most directory from the stack

pwd


-------------Viewing Files-----------------------------------------------------------------------------------------------

cat Used for viewing files that are not very long; it does not provide any scroll-back.

tac Used to look at a file backwards, starting with the last line.

less Used to view larger files because it is a paging program. It pauses at each screen full of text, provides scroll-back capabilities, and lets you search and navigate within the file. Note: Use / to search for a pattern in the forward direction and ? for a pattern in the backward direction. An older program named more is still used, but has fewer capabilities: "less is more".

tail Used to print the last 10 lines of a file by default. You can change the number of lines by doing -n 15 or just -15 if you wanted to look at the last 15 lines instead of the default.

head The opposite of tail; by default, it prints the first 10 lines of a file.


----------------touch------------------------------------------------------------------------------------------------------

$ touch <filename>

$ touch -t 12091600 myfile  the -t option allows you to set the date and timestamp of the file to a specific value. Myfile file's timestamp to 4 p.m., December 9th (12 09 1600)


------------mkdir---------------------------------------------------------------------------------------------------------

mkdir and rmdir

mkdir sampdir   It creates a sample directory named sampdir under the current directory. 

mkdir /usr/sampdir   It creates a sample directory called sampdir under /usr

Removing a directory is done with rmdir. The directory must be empty or the command will fail. To remove a directory and all of its contents you have to do rm -rf


------------Moving, Renaming or Removing a File---------------------------------------------------------------

mv Rename a file 

rm Remove a file 

rm –f Forcefully remove a file

rm –i Interactively remove a file (to prompt before every removal)


--------------Renaming or Removing a Directory-----------------------------------------------------------------

rmdir works only on empty directories; otherwise you get an error. While typing rm –rf is a fast and easy way to remove a whole filesystem tree recursively

mv Rename a directory

rmdir Remove an empty directory

rm -rf Forcefully remove a directory recursively


----------------Modifying the Command Line Prompt------------------------------------------------------------

The PS1 variable is the character string that is displayed as the prompt on the command line

user and the host system name to show up on the command line as in:

student@c8 $

The prompt above could be implemented by setting the PS1 variable to: \u@\h \$

$ echo $PS1

\$

$ PS1="\u@\h \$ "

student@c8 $ echo $PS1

\u@\h \$

student@c8 $

By convention, most systems are set up so that the root user has a pound sign (#) as their prompt


------------Standard File Streams------------------------------------------------------------------------------------

Name Symbolic Name Value Example

standard input stdin 0 keyboard

standard output stdout 1 terminal

standard error stderr 2 log file


-------------I/O Redirection--------------------------------------------------------------------------------------------

we can change its input source by using the less-than sign ( < ) followed by the name of the file to be consumed for input data:

$ do_something < input-file

If you want to send the output to a file, use the greater-than sign (>) as in:

$ do_something > output-file

Because stderr is not the same as stdout, error messages will still be seen on the terminal windows in the above example

If you want to redirect stderr to a separate file, you use stderr’s file descriptor number (2), the greater-than sign (>), followed by the name of the file you want to hold everything the running command writes to stderr:

$ do_something 2> error-file


Note: By the same logic, do_something 1> output-file is the same as do_something > output-file.

A special shorthand notation can send anything written to file descriptor 2 (stderr) to the same place as file descriptor 1 (stdout): 2>&1.

$ do_something > all-output-file 2>&1

bash permits an easier syntax for the above:

$ do_something >& all-output-file


------------Pipes----------------------------------------------------------------------------------------------------------

$ command1 | command2 | command3

The above represents what we often call a pipeline, and allows Linux to combine the actions of several commands into one.


---------------locate-------------------------------------------------------------------------------------------------------

The locate utility program performs a search taking advantage of a previously constructed database of files and directories on your system, matching all entries that contain a specified character string

$ locate zip | grep bin   which will list all the files and directories with both zip and bin in their name


--------------Wildcards and Matching File Names----------------------------------------------------------------

Wildcard Result

? Matches any single character

* Matches any string of characters

[set] Matches any character in the set of characters, for example [adf] will match any occurrence of a, d, or f

[!set] Matches any character not in the set of characters


if you know only the first two letters are 'ba' of a three-letter filename with an extension of .out, type ls ba?.out

To search for files using the * wildcard, replace the unknown string with *. For example, if you remember only that the extension was .out, type ls *.out.



-------------Package Management Systems on Linux------------------------------------------------------------

Operation RPM deb

Install package rpm -i foo.rpm dpkg --install foo.deb

Install package, dependencies yum install foo apt-get install foo

Remove package rpm -e foo.rpm dpkg --remove foo.deb

Remove package, dependencies yum remove foo apt-get autoremove foo

Update package rpm -U foo.rpm dpkg --install foo.deb

Update package, dependencies yum update foo apt-get install foo

Update entire system yum update apt-get dist-upgrade

Show all installed packages rpm -qa or dpkg --list

yum list installed

Get information on package rpm -qil foo dpkg --listfiles foo

Show packages named foo yum list "foo" apt-cache search foo

Show all available packages yum list apt-cache dumpavail foo

What package is file part of? rpm -qf file dpkg --search file


---------------Process Types--------------------------------------------------------------------------------------------

Process Type Description

Interactive Processes Need to be started by a user, either at a command line or through a                                                            graphical interface such as an icon or a menu                                                                                                 selection. bash, firefox, top

Batch Processes Automatic processes which are scheduled from and then                                                                            disconnected from the terminal. These tasks are queued and work on                                                         a FIFO (First-In, First-Out) basis. updatedb, ldconfig

Daemons         Server processes that run continuously. Many are launched during                                                            system startup and then wait for a user or system request indicating                                                            that their service is required. httpd, sshd, libvirtd

Threads Lightweight processes. These are tasks that run under the umbrella of a main process, sharing memory and other resources, 

but are scheduled and run by the system on an individual basis. An individual thread can end without terminating the whole process and 

a process can create new threads at any time. Many non-trivial programs are multi-threaded. firefox, gnome-terminal-server

Kernel Threads Kernel tasks that users neither start nor terminate and have little control over. These may perform actions like moving a thread from one CPU to another,

or making sure input/output operations to disk are completed kthreadd, migration, ksoftirqd

-------------Process and Thread IDs---------------------------------------------------------------------------------

ID Type Description

Process ID (PID) Unique Process ID number

Parent Process ID (PPID) Process (Parent) that started this process. If the parent dies, the PPID                                                         will refer to an adoptive parent; on recent kernels, this is kthreadd                                                            which has PPID=2.

Thread ID (TID) Thread ID number. This is the same as the PID for single-threaded                                                            processes. For a multi-threaded process, each thread shares the same                                                         PID, but has a unique TID.


--------Terminating a Process-----------------------------------------------------------------------------------------

To terminate a process, you can type kill -SIGKILL <pid> or kill -9 <pid>.


---------Process Priority------------------------------------------------------------------------------------------------

The priority for a process can be set by specifying a nice value, or niceness, for the process. The lower the nice value, the higher the priority. Low values are assigned to important processes, while high values are assigned to processes that can wait longer.

In Linux, a nice value of -20 represents the highest priority and +19 represents the lowest.

ps

ps lf   to see priority

renice +5 3077 (id)

ps


--------------Load Averages-------------------------------------------------------------------------------------------

The load average is the average of the load number for a given period of time. It takes into account processes that are:

Actively running on a CPU

Considered runnable, but waiting for a CPU to become available

Sleeping: i.e. waiting for some kind of resource (typically, I/O) to become available.

The load average can be viewed by running w, top or uptime


-----------Interpreting Load Averages-------------------------------------------------------------------------------

The load average is displayed using three numbers (0.45, 0.17, and 0.12)

0.45: For the last minute the system has been 45% utilized on average.

0.17: For the last 5 minutes utilization has been 17%.

0.12: For the last 15 minutes utilization has been 12%.

----------------------------------------------------------------------------------------------------------------------------


Linux Interview Questions

1 comment:

  1. You have given great content here.startup service I am glad to discover this post as I found lots of valuable data in your article. Thanks for sharing an article like this.

    ReplyDelete

Powered by Blogger.