Signals in Linux; trap command – practical example

The SIGNALS in linux

The signals are the response of the kernel to certain actions generated by the user / by a program or an application and the I/O devices.
The linux trap command gives us a best view to understand the SIGNALS and take advantage of it.
With trap command can be used to respond to certain conditions and invoke the various activities when a shell receives a signal.
The below are the various Signals in linux.

vamshi@linuxcent :~] trap -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX

Lets take a look at some Important SIGNALS and their categorization of them:

Job control Signals: These Signals are used to control the Queuing the waiting process
(18) SIGCONT, (19) SIGSTOP , (20) SIGSTP

Termination Signals: These signals are used to interrupt or terminate a running process
(2) SIGINT , (3) SIGQUIT, (6) SIGABRT,  (9) SIGKILL,  (15) SIGTERM.

Async I/O Signals: These signals are generated when data is available on a Input/Output device or when the kernel services wishes to notify applications about resource availability.
(23) SIGURG,  (29) SIGIO,  (29) SIGPOLL.

Timer Signals: These signals are generated when application wishes to trigger timers alarms.
(14) SIGALRM,  (27) SIGPROF,  (26) SIGVTALRM.

Error reporting Signals: These signals occur when running process or an application code endsup into an exception or a fault.
(1) SIGHUP, (4) SIGILL, (5) SIGTRAP, (7) SIGBUS, (8) SIGFPE,  (13) SIGPIPE,  (11) SIGSEGV, (24) SIGXCPU.

Trap command Syntax:

trap [-] [[ARG] SIGNAL]

ARG is a command to be interpreted and executed when the shell receives the signal(s) SIGNAL.

If no arguments are supplied, trap prints the list of commands associated with each signal.
to unset the trap a – is to be used followed by the [ARG] SIGNAL] which we will demonstrate in the following section.

How to set a trap on linux through the command line?

[vamshi@linuxcent ~]$ trap 'echo -e "You Pressed Ctrl-C"' SIGINT

Now you have successfully setup a trap:>

When ever you press Ctrl-c on your keyboard, the message “You Pressed Ctrl-C” gets printed.

[vamshi@linuxcent ~]$ ^CYou Pressed Ctrl-C
[vamshi@linuxcent ~]$ ^CYou Pressed Ctrl-C
[vamshi@linuxcent ~]$ ^CYou Pressed Ctrl-C

Now type the trap command and you can see the currently set trap details.

[vamshi@node01 ~]$ trap
trap -- 'echo -e "You Pressed Ctrl-C"' SIGINT
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU

To unset the trap all you need to do is to run the following command,

[vamshi@node01 ~]$ trap - 'echo -e "You Pressed Ctrl-C"' SIGINT

The same can be evident from the below output:

[vamshi@node01 ~]$ trap
trap -- '' SIGTSTP
trap -- '' SIGTTIN
trap -- '' SIGTTOU
[vamshi@node01 ~]$ ^C
[vamshi@node01 ~]$ ^C

What is trap command in Linux?

A built-in bash command that is used to execute a command when the shell receives any signal is called `trap`. When any event occurs then bash sends the notification by any signal. Many signals are available in bash. The most common signal of bash is SIGINT (Signal Interrupt).

What is trap command in bash?

If you’ve written any amount of bash code, you’ve likely come across the trap command. Trap allows you to catch signals and execute code when they occur. Signals are asynchronous notifications that are sent to your script when certain events occur.

How do you Ctrl-C trap?

To trap Ctrl-C in a shell script, we will need to use the trap shell builtin command. When a user sends a Ctrl-C interrupt signal, the signal SIGINT (Signal number 2) is sent.

What is trap shell?

trap is a wrapper around the fish event delivery framework. It exists for backwards compatibility with POSIX shells. For other uses, it is recommended to define an event handler. The following parameters are available: ARG is the command to be executed on signal delivery.

What signals Cannot be caught?

There are two signals which cannot be intercepted and handled: SIGKILL and SIGSTOP.

How does shell trap work?

The user sets a shell trap. If the user is hit by a physical move, the trap will explode and inflict damage on the opposing Pokémon. The user sets a shell trap. If the user is hit by a physical move, the trap will explode and inflict damage on opposing Pokémon.

How do I wait in Linux?

Approach:

  1. Creating a simple process.
  2. Using a special variable($!) to find the PID(process ID) for that particular process.
  3. Print the process ID.
  4. Using wait command with process ID as an argument to wait until the process finishes.
  5. After the process is finished printing process ID with its exit status.

How use stty command in Linux?

  1. stty –all: This option print all current settings in human-readable form. …
  2. stty -g: This option will print all current settings in a stty-readable form. …
  3. stty -F : This option will open and use the specified DEVICE instead of stdin. …
  4. stty –help : This option will display this help and exit.

Can I trap Sigkill?

You can’t catch SIGKILL (and SIGSTOP ), so enabling your custom handler for SIGKILL is moot. You can catch all other signals, so perhaps try to make a design around those. be default pkill will send SIGTERM , not SIGKILL , which obviously can be caught.

What signal is Ctrl D?

Ctrl + D is not a signal, it’s EOF (End-Of-File). It closes the stdin pipe. If read(STDIN) returns 0, it means stdin closed, which means Ctrl + D was hit (assuming there is a keyboard at the other end of the pipe).

How to Shutdown or Reboot a remote Linux Host from commandline

The Shutdown process in a Linux system is an intelligent chain process where in the system ensures the dependent process have successfully terminated.

TL;DR:

Difference between the Halt and Poweroff in Linux?
What is a Cold Shutdown and Warm Shutdown?
Linux System System Halt : The Halt process instructs the hardware to Stop the functioning of the CPU. Can be referred as a Warm Shutdown.
Linux System Poweroff/Shutdown : The Poweroff function sends the ACPI(Advanced Configuration and Power Interface) to power down the system. Can be referred as a Cold Shutdown.

As you may be aware the Linux runtime environment is a duo combination of processes running in User space and the Kernel space, All the major system activities and resources are initiated and governed and terminated by Kernel space.
So we got the Kernel space and the User space, The kernel space is where all the reseurce related processes run, which follows a finite behaviour, and the the userspace where the processes are dependent on the user actions, most of the userspace programs depend on the kernel space and make a context switch to get the CPU scheduling and such..
So, In the sequence of Shutdown on a linux machine, the userspace processes are first terminated in a systematic fashion through the scripts triggered by the core systemd processes which ensures clean exit and termination all the processes.

The Linux system provides us quite a few commands to enforce fast shutdown or a graceful shutdown of the operating system, each having their own consequences.

Firstly the init or the systemd which is the pid 1 process is what controls the runlevel of the system and it determines which processes are launched and running in that runlevel

The init is a powerful command which executes the runlevel it is told to.
Here the init 0 proceeds to Power-off the machine

$ sudo init 0

Here the init 6 proceeds to Reboot the machine

$ sudo init 6

These commands are real quick as it triggers the kernel space shutdown invocation process.. most often resulting in unclean termination of processes resulting system recovery and journaling while booting.

The following commands Shutdown the machine in seconds after issuing the command But tend to follow the kill sequence and clean exit of the processed.

$ sudo shutdown
$ sudo poweroff
$ sudo systemctl poweroff

Prints a wall message to all users.
All the processes are killed and the volumes are unmounted or converted to be in Read-Only mode while system power off is in progress.
Puts the system into a complete poweroff mode cutting out power supply to the machine completely.

$ sudo halt
$ sudo systemctl halt

Prints a message of “System halted” and Puts the machine in halt mode
If the --force or -f when specified twice the operation is immediately executed without terminating any processes or unmounting any file systems and resulting in data loss

The servers can only be brought back online through physical poweron or Remote Power manager console such as IPMI or ILOM.

To reboot or [/code]systemctl kexec[/code] will to restart the operating system which is one power cycle or equivalent of shutdown followed by the startup.

$ sudo reboot

$ sudo systemctl kexec

$ sudo systemctl reboot

If the --force or -f when specified twice the operation is immediately executed without terminating any processes or unmounting any file systems and resulting in data loss

 

It is important to understand that the commands are all softlinks to systemctl shutdown command. and ensure in proper shutdown sequence process

[vamshi@linuxcent cp-command]$ ls -l /usr/sbin/halt
lrwxrwxrwx. 1 root root 16 Jan 13 14:41 /usr/sbin/halt -> ../bin/systemctl
[vamshi@linuxcent cp-command]$ ls -l /usr/sbin/reboot
lrwxrwxrwx. 1 root root 16 Jan 13 14:41 /usr/sbin/reboot -> ../bin/systemctl
[vamshi@linuxcent cp-command]$ ls -l /usr/sbin/poweroff
lrwxrwxrwx. 1 root root 16 Jan 13 14:41 /usr/sbin/poweroff -> ../bin/systemctl

It is important to observe that all the commands are softlink to the systemctl process, When issuing a shutdown or reboot

The best practice to poweroff the system by enabling broadcast the notification message to all the users connected actively either through the Pseudo remote connection terminal or TTY terminals, Demonstrated as follows:

$ sudo systemctl poweroff

# this writes an entry into the journal, the wtmp and broadcasts the shutdown message to all the users connected through PTS and TTY terminals

What is the difference between systemctl poweroff and systemctl halt ?

The Linux System when put to a Halt state, stops the all the applications and ensures they’re safely exited, filesystems and volumes are unmounted and it is taken into a halted state where in the power connection is still active. And Can only be brought  online with a power reset effectively with a simple reset.
The Halt process instructs the hardware to Stop the functioning of the CPU.
Commonly can be referred as a Warm Shutdown.

Below is the screenshot to demonstrate the same
systemctl halt command in linux

The Poweroff function sends the ACPI(Advanced Configuration and Power Interface) to power down the system.
The Linux System when put to a Poweroff state it becomes completely offline following the systematical clean termination of processes.. and power input is cut off to the external peripherals, which is also sometimes called as cold shutdown, and the startup cold start.
Commonly can be referred to as a Cold Shutdown.

If you found the article worth your time, Please share your inputs in the comments section and share your experiences with shutdown and reboot issues

Can I reboot Linux remotely?

How to shutdown the remote Linux server. You must pass the -t option to the ssh command to force pseudo-terminal allocation. The shutdown accepts -h option i.e. Linux is powered/halted at the specified time.

Can you reboot a server remotely?

Open command prompt, and type “shutdown /m \\RemoteServerName /r /c “Comments”“. … Another command to restart or shutdown the Server remotely is Shutdown /i. Type Shutdown /i on the command prompt and it will open another dialogue box.

What is the Linux command to reboot?

To reboot Linux using the command line:

  1. To reboot the Linux system from a terminal session, sign in or “su”/”sudo” to the “root” account.
  2. Then type “ sudo reboot ” to reboot the box.
  3. Wait for some time and the Linux server will reboot itself.

How do I reboot from remote desktop?

Procedure. Use the Restart Desktop command. Select Options > Restart Desktop from the menu bar. Right-click the remote desktop icon and select Restart Desktop.

What does sudo reboot do?

sudo is short for “Super-user Do”. It has no effect on the command itself (this being reboot ), it merely causes it to run as the super-user rather than as you. It is used to do things that you might not otherwise have permission to do, but doesn’t change what gets done.

How do I remotely turn on a Linux server?

Enter the BIOS of your server machine and enable the wake on lan/wake on network feature. …
Boot your Ubuntu and run “sudo ethtool -s eth0 wol g” assuming eth0 is your network card. …
run also “sudo ifconfig” and annotate the MAC address of the network card as it is required later to wake the PC.

How do I restart a terminal server remotely?

From the remote computer’s Start menu, select Run, and run a command line with optional switches to shut down the computer:
To shut down, enter: shutdown.
To reboot, enter: shutdown –r.
To log off, enter: shutdown –l

How do I send Ctrl Alt Del to remote desktop?

Press the “CTRL,” “ALT” and “END” keys at the same time while you are viewing the Remote Desktop window. This command executes the traditional CTRL+ALT+DEL command on the remote computer instead of on your local computer.

How do I remotely restart a server by IP address?

Type “shutdown -m \ [IP Address] -r -f” (without quotes) at the command prompt, where “[IP Address]” is the IP of the computer you want to restart. For example, if the computer you want to restart is located at 192.168. 0.34, type “shutdown -m \ 192.168.

How do I reboot from command prompt?

  1. From an open command prompt window:
  2. type shutdown, followed by the option you wish to execute.
  3. To shut down your computer, type shutdown /s.
  4. To restart your computer, type shutdown /r.
  5. To log off your computer type shutdown /l.
  6. For a complete list of options type shutdown /?
  7. After typing your chosen option, press Enter.

How does Linux reboot work?

The reboot command is used to restart a computer without turning the power off and then back on. If reboot is used when the system is not in runlevel 0 or 6 (i.e., the system is operating normally), then it invokes the shutdown command with its -r (i.e., reboot) option.

BASH “switch case” in Linux with practical example

The switch case in BASH is more relevant and is widely used among the Linux admins/Devops folks to leverage the power of control flow in shell scripts.

As we have seen the if..elif..else..fi Control Structure: Bash If then Else. The switch case has a stronger case where it really simplifies out the control flow by running the specific block of bash code based on the user selection or the input parameters.

Let’s take a look at the simple Switch case as follows:

OPTION=$1
case $OPTION in
choice1)
Choice1 Statements
;;

choice2)
Choice2 Statements
;;

choiceN)
ChoiceN Statements
;;

*)
echo “User Selected Choice not present”
exit 1

esac

The OPTION is generally read from user input and upon this the specific choice case block is invoked.

Explanation:
In the switch command the control flow is forwarded to case keyword and stops here, it checks for the suitable match to pass over the control to relevant OPTION/CHOICE statement block. Upon the execution of the relevant CHOICE statements the case is exited once the control flow encounters esac keyword at the end.

Using the Pattern match
The control flow in bash identifies the case options and proceeds accordingly.
There can be cases where you can match the Here you might have observed that the user input the regular expression and the logical operators using the | for the input case

#! /bin/bash

echo -en "Enter your logins\nUsername: "
read user_name 
echo -en "Password: "
read user_pass 
while [ -n $user_name -a -n $user_pass ]
do

case $user_name in
    ro*|admin)
        if [ "$user_pass" = "Root" ];
        then
            echo -e "Authentication succeeded \ n You Own this Machine"
	    break
        else
            echo -e "Authentication failure"
            exit
        fi
    ;;
    jenk*)
	if [ "$user_pass" = "Jenkins" ];
	then
		echo "Your home directory is /var/lib/jenkins"
	    	break
	else
        	echo -e "Authentication failure"
	fi
        break
    ;;
    *)
        echo -e "An unexpected error has occurred."
        exit
    ;;
esac

done

You should kindly note that the regex used for the cases at ro*|admin and jenk*

We now have demonstrated by entering the username as jenkins and this will get matched with the jenkins case the control flow successfully enters into relevant block of code, checking the password match or not is not relevant for us as we are only concerned till the case choice selection.
We have named the switch case into a script switch-case.sh and run it, Here are the results.

OUTPUT :

[vamshi@node02 switch-case]$ sh switch-case.sh
Enter your logins
Username: jenkins
Password: Jenkins
Your home directory is /var/lib/jenkins

We have entered the correct password and successfully runs the jenkins case block statements

We shall also see the or ro*|admin case, demonstrated as follows.

[vamshi@node02 switch-case]$ sh switch-case.sh 
Enter your logins
Username: root
Password: Root
Authentication succeeded \ n You Own this Machine

We now test the admin username and see the results.

[vamshi@node02 switch-case]$ sh switch-case.sh 
Enter your logins
Username: admin
Password: Root
Authentication succeeded \ n You Own this Machine

Here is a more advanced script used to deploy a python application using the switch case..
Please refer to the Command line arguments section for user input

A complete functional Bash switch case can be seen at https://github.com/rrskris/python-deployment-script/blob/master/deploy-python.sh

Please feel free to share your experiences in comments.

What is switch in bash?

The Bash case statement has a similar concept with the Javascript or C switch statement. The main difference is that unlike the C switch statement, the Bash case statement doesn’t continue to search for a pattern match once it has found one and executed statements associated with that pattern.

How do you write a switch case in shell?

In shell scripting switch case is represented using keywords case and esac which will do multilevel branching and checking in a better way than multiple if-else conditions. Switch case will need an expression which it needs to evaluate and need to perform multiple operations based on the outcome of the expression.

How does case work in bash?

5 Bash Case Statement Examples

  1. Case statement first expands the expression and tries to match it against each pattern.
  2. When a match is found all of the associated statements until the double semicolon (;;) are executed.
  3. After the first match, case terminates with the exit status of the last command that was executed.

What is the use of switch case in Unix shell scripting?

Switch case in shell scripts is an efficient alternative to the if-elif-else statement that we learned previously. The concept of the switch case statements is that we provide different cases (conditions) to the statement that, when fulfilled, will execute specific blocks of commands.

Which command is used for switch case in Linux script?

esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

What is a switch or option in command line?

A command line switch (also known as an option, a parameter, or a flag) acts as a modifier to the command you are issuing in the Command Prompt window, in a batch file, or in other scripts. Usually, a switch is a single letter preceded by a forward slash.

What is ESAC bash?

The esac keyword is indeed a required delimiter to end a case statement in bash and most shells used on Unix/Linux excluding the csh family. The original Bourne shell was created by Steve Bourne who previously worked on ALGOL68. This language invented this reversed word technique to delimit blocks.

What is Getopts in shell script?

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt. The predecessor to getopts was the external program getopt by Unix System Laboratories.

 

date command formatting with practical examples in Linux / Unix

Date Command in Linux is very extensive and dynamic, provides very rich date formatting and is greatly customizable for working with scripts which depend on time based invocations.

Linux date command can also be used to set the system date and it requires the root permission.

Lets run date command and examine the output.

[vamshi@node02 log]$ date
Wed Apr 1 13:52:21 UTC 2020

Now lets examine some of the most useful options that comes with the date command.

Firstly date command along with -s or --set option can take for following format to set the new system time and date.

How to set the system date in Linux using date command?

[vamshi@node02 log]$ sudo date -s 'Apr 01 2020 13:52:59 UTC'
Wed Apr 1 13:52:59 UTC 2020

The date can also be setup in shot hand notation as follows,but it is more cryptic

[vamshi@node02 log]$ sudo date 040113522020.50
Wed Apr 1 13:52:50 UTC 2020
$ sudo date mmddHHMMyyyy.SS

The format is month of the Year(mm),day of the month(dd),Hour of the day(HH),minute of the Hour(MM) and the Year(yyyy),and the Seconds of the minute(.SS)
Now, Lets dive deep and get to know the date options and Demonstration practical examples in this tutorial:

Another Important Option is -d or –date=”String” which can display the time described
Lets see some examples as follows:

By running the date command, we get an elaborate time and date format along with the TimeZone information.
To covert the Epoc time to human readable date, we can use date command as follows:

[vamshi@node02 log]$ date -d"@1585749164"
Wed Apr 1 13:52:44 UTC 2020

If you want to get a future date then use:

[vamshi@linuxcent ~]$ date -d "+130 days"
Sun Aug 16 02:07:35 UTC 2020

Date command offers a great flexibility to extract past and future dates as we will show below:

$ date "+ %F" -d “+30 days”
$ date "+ %F" --date “+30 days”

To get the date in history; go back to a date some days ago in Linux

[vamshi@node02 log]$ date -d "17 days ago"
Sun Mar 15 13:52:45 UTC 2020

Here we present some of the more useful Format options:

Date Format Command Explanation Result
date +”%a” Prints the Abbreviated Day of the Week Sat-Sun Wed
date +”%A” Prints the Day of the Week Saturday-Sunday Wednesday
date +”%b” Prints Abbreviated Month Jan-Dec Apr
date +”%B” Print un-abbreviated month January-December April
date +”%c” Prints Full Current Date and time format Wed Apr 1 13:52:43 UTC 2020
date +”%D” Prints dd/mm/yy date format 04/01/2020
date +”%d” Prints day of the month (01-31) 01
date +”%D” Prints Date in MM/DD/YY 04/01/20
date +”%e” Prints the Day of the month 01
date +”%F” Prints only the Full date as YYYY-MM-DD 2020-04-01
date +”%H” Prints the hour 00-23 13
date +”%I” Prints the hour in 00-12 01
date +”%j” Prints Julian day of the Year(001-366) 092
date +”%M” Prints the Minute of the hour 00-59 52
date +”%m” Prints the month of the year 01-12 04
date +”%n” Prints the newline character Newline/Empty line
date +”%N” Prints the nanoseconds counts 036416306
date +”%P” Prints AM/PM in the day PM
date +”%r” Get only time in AM/PM notation 13:52:43 PM
date +”%S” Get the current seconds count in the minute (00-60) 43
date +”%s” Get the number of seconds since 1st January 1970 (Epoch time) 1585749164
date +”%T” Time in 24 Hour format HH:MM:YY 13:52:43
date +”%u” Get  current day of the week
1-7
3 for Wednesday
date +”%U” Get the current week of the Year considering Sunday as first week 13
date +”%V” Get the current week of the Year considering Monday as first week 14
date +”%y” or date +”%g” Prints only the last two digits of Year 20
Date +“%Y” or date +”%F” Prints Year in YYYY format 2020
Date +“%z” Prints the current Timezone difference from UTC 00 – for UTC
date +”%Z” Prints Alphabetic time zone abbreviation UTC

How to write the current system time to the Machine’s hardware clock ?

The command hwclock can do that for us.
[/code] # sudo hwclock [OPTIONS][/code]

Lets see a practical example where our Hardware clock was 1 hour and 13 mins behind the actual system time .

[vamshi@node02 ~]$ sudo hwclock
Wed 01 Apr 2020 07:35:05 AM UTC -0.454139 seconds
[vamshi@node02 ~]$ date
Wed Apr 01 08:43:13 UTC 2020

Setting the hardware clock time to system time with option -w or --systohc as seen below.

[vamshi@node02 ~]$ sudo hwclock -w

Confirm it with hwclock command as follows:

[vamshi@node02 ~]$ sudo hwclock
Wed 01 Apr 2020 08:44:05 AM UTC -0.538163 seconds

Most of the times the hardware clock will be out of sync with the system time and its a good practice to set the hardware clock in sync and comes in real handy during the system reboots.

What is the date format in Unix?

Below is a list of common date format options with examples output. It works with the Linux date command line and the mac/Unix date command line.

Date Format Option Meaning Example Output
date +%m-%d-%Y MM-DD-YYYY date format 05-09-2020
date +%D MM/DD/YY date format 05/09/20

How do I format a date in Linux?

These are the most common formatting characters for the date command:
  1. %D – Display date as mm/dd/yy.
  2. %Y – Year (e.g., 2020)
  3. %m – Month (01-12)
  4. %B – Long month name (e.g., November)
  5. %b – Short month name (e.g., Nov)
  6. %d – Day of month (e.g., 01)
  7. %j – Day of year (001-366)
  8. %u – Day of week (1-7)

What %D format in date command does?

%D: Display date as mm/dd/yy.

%d: Display the day of the month (01 to 31). %a: Displays the abbreviated name for weekdays (Sun to Sat). %A: Displays full weekdays (Sunday to Saturday).

How do you change the date in Unix?

The basic way to alter the system’s date in Unix/Linux through the command line environment is by using “date” command. Using date command with no options just displays the current date and time. By using the date command with the additional options, you can set date and time.

What is the date format?

Date Format Types
Format Date order Description
1 MM/DD/YY Month-Day-Year with leading zeros (02/17/2009)
2 DD/MM/YY Day-Month-Year with leading zeros (17/02/2009)
3 YY/MM/DD Year-Month-Day with leading zeros (2009/02/17)
4 Month D, Yr Month name-Day-Year with no leading zeros (February 17, 2009)

How can I get yesterday date in Unix?

  1. Use perl: perl -e ‘@T=localtime(time-86400);printf(“%02d/%02d/%02d”,$T[4]+1,$T[3],$T[5]+1900)’
  2. Install GNU date (it’s in the sh_utils package if I remember correctly) date –date yesterday “+%a %d/%m/%Y” | read dt echo ${dt}
  3. Not sure if this works, but you might be able to use a negative timezone.

How do I display yesterday’s date in Linux?

Yesterday date YES_DAT=$(date –date=’ 1 days ago’ ‘+%Y%d%m’)
Day before yesterdays date DAY_YES_DAT=$(date –date=’ 2 days ago’ ‘+%Y%d%m’)

Which command is used for displaying date and calendar in Unix?

Which command is used for displaying date and calendar in UNIX? Explanation: date command is used for displaying the current system date and time while cal command is used to see the calendar of any specific month/year.

Which command is used for displaying date in the format dd mm yyyy?

To use the date in MM-YYYY format, we can use the command date +%m-%Y. To use the date in Weekday DD-Month, YYYY format, we can use the command date +%A %d-%B, %Y.

What does df command do in Linux?

Display Information of /home File System. To see the information of only device /home file systems in human-readable format use the following command.

sed – The Stream editor in Linux

The Stream Editor(sed) is a text manipulation program, that takes the input from stdin and from the text files, It writes to the stdout and modifies the input files accordingly. The text manipulation means deleting characters and words; Inserting text into the source file on the fly.
This is a transformation operation and quiet a handy skill to have for someone working in linux shell.

The sed comprises of two operations, The first one is a regex search and match operation and the second one is replace operation accordingly. This combines the greater power of search and replace of text from stdin and from the flat files.
Here is general syntax of sed command is:

# sed [-n] -e 'options/commands' files
# sed [-n] -f sed-scriptfile
# sed -i filename -e 'options/commands'

-e is the edit option used on the cli.
-f to take the sed commands from the scriptfile
-n or –quiet option supresses the output unless specified with -p or -s

We will look at some of the notable options the sed offers.

Some practical usecases, But before that we take at our sample README.txt.

Substitute and Replace with sed:

sed command offers the -s option which is exclusive for search and replace operation also known as search and substitution.

[vamshi@node02 sed]$ echo Welcome to LinuxCent | sed -e 's/e/E/'
WElcome to LinuxCent

This replaces the e to E in the input received and prints to stdout.
We can apply the same to the Text file and achieve the same results.

[vamshi@node02 ~]$ sed -e 's|u|U|' README.txt
centos 	
debian 	
redhat 	
Ubuntu

But the important thins to be noted is that the first occurring pattern match per line is only replaced. In out case only 1 letter per line as the letter u is replaced in ubuntu by U.

Substitute and replace globally using the option -g.

We run the below command stdin input stream as show below:

[vamshi@node02 sed]$ echo Welcome to LinuxCent | sed -e 's/e/E/g'
WElcomE to LinuxCEnt

Running the global option g on the fileinput as shown below.

[vamshi@node02 ~]$ sed -e 's/u/U/g' README.txt
centos 
debian 	
redhat 	
UbUntU 	

Substitute the later occurrences using sed. We search for the 3rd occurrence of letter u and if matched replace it with U.

[vamshi@node02 ~]$ sed -e 's/u/U/3g' README.txt
centos 	
debian 	
redhat 	
ubuntU

In the above case we have seen the lowercase u has been replaced with Uppercase U at the third occurrence.
Now let us append the word to the end of the each line using the below syntax:

[vamshi@node02 ~]$ sed -e 's/$/ Linux/' README.txt
centos Linux
debian Linux
redhat Linux
ubuntu Linux

Adding text to the file data at the beginning of each line and writing to the stdout.

[vamshi@node02 Linux-blog]$ sed -e 's/^/Distro name: /' Distronames.txt 
Distro name: centos Linux
Distro name: debian Linux
Distro name: redhat Linux
Distro name: ubuntu Linux

sed Interactive Editor: How to write the modified sed data into the same text file?

We can use the -i Interactive Editor option in combination with most other sed options, the input file content is directly modified according to the command pattern.
Example Given.

[vamshi@node02 sed]$ sed -e 's/e/E/g' -i intro.txt
[vamshi@node02 sed]$ cat intro.txt
WElcomE to LinuxCEnt

We use the -i option to append some text to a file as demonstrated as follows:

[vamshi@node02 Linux-blog]$ sed -i 's/$/ Linux/' README.txt
[vamshi@node02 Linux-blog]$ cat README.txt 
centos Linux
debian Linux
redhat Linux
ubuntu Linux

Here we append the words Linux to end of the each line
Alternate to -i you can also use the output redirection to write to a new file  as shown below.

[vamshi@node02 ~]$ sed -e 's/$/ Linux/' README.txt > OSnames.txt

Delete Operations with sed

Delete all the lines containing the pattern:

[vamshi@node02 ~]$ sed -e /ubu/d README.txt
centos Linux 
debian Linux 
redhat Linux

Here we matched the word ubuntu and hence have deleted that line from output.

We can use the ! inverse operator with the delete, demonstrated as follows:

[vamshi@node02 Linux-blog]$ sed -e '/ubu/!d' Distronames.txt
ubuntu Linux

Using the Ranges in sed

Extracting only the specific /BEGIN and /END pattern using sed.

[vamshi@node02 Linux-blog]$ cat Distronames.txt | sed -n -e '/^centos/,/^debian/p'
centos Linux	
debian Linux

Substitution of Range of lines

[vamshi@node02 Linux-blog]$ sed -e  '1,3s/u/U/' Distronames.txt
centos LinUx.	
debian LinUx.	
redhat LinUx.	
ubuntu Linux.

Delete the . at the end of each line

[vamshi@node02 Linux-blog]$ sed -e 's/.$//' Distronames.txt

Print only the lines containing the word “hat”

[vamshi@node02 Linux-blog]$ sed -n -e '/hat/p' Distronames.txt 
redhat Linux

Use sed to Match the pattern insert text.
Insert the lines before the matched pattern in file

[vamshi@node02 Linux-blog]$ cat README.txt | sed -e '/centos/i\Distro Names '
Distro Names 
centos
debian
redhat
ubuntu

The above scenario we have inserted the sentence “Distro Names” before the occurrence of the work centos.

[vamshi@node02 Linux-blog]$ cat Distronames.txt | sed -e '1a\------------'
Distro Names 
------------
centos
debian
redhat
ubuntu

The ———— are appended to the text after the 1st line

How to create user account in Linux

The Linux system provides a couple of command line utilities to create new users on the system

As we are aware, the Linux login has the essential fields listed as follows:

  • A unique system wide username,
  • A Strong password,
  • The home directory and
  • A login shell.

These are the mandatory fields to enable account creation.

The other fields are the UID and GID numbers associated with User an Group name numerical IDs which will be generated sequentially allocated by the Linux Kernel

We can do a broad categorization of login accounts into 2 types, those are the Privileged and the normal user.

The Absolute Privileged account is root which comes by default in all the linux machines.

The normal account can be enabled with root Privileged by assigning user to certain groups and providing elevated access in the scope.

What is the Process to create a User account in Linux?

The user creation has to be done with root privileges using useradd command.

$ sudo useradd newuser

Now it’s time to enter the password

$ sudo passwd newuser

How to check if the userid is present and active on the system?

The new user details will be updated to /etc/passwd file and the login information updated to /etc/shadow

Now let’s check if the user account is created and has a valid shell

vamshi@node03:/$ grep vamshi /etc/passwd

vamshi:x:1001:1001::/home/vamshi:/bin/bash

How to Add the user to new groups in Linux?

Usermod command line linux utility enables to add user to groups and the ability to add an existing user to new groups additionally or overwrite the group membership

$ usermod -aG dockerroot wheel vamshi

The option -a: appends the user to two new groups called dockerroot and wheel with out overwriting the existing user assigned groups, violating this option will restrict the newuser to be part of only the mentioned groups in the command

How to check and verify if the user is a member of group in Linux?

[vamshi@node02 Linux-blog]$ id vamshi
uid=1001(vamshi) gid=1001(vamshi) groups=1001(vamshi),0(root),10(wheel),992(dockerroot)

How to Verify the Login Confirmation in Linux?

From the root user account run the command: su - newuser to check the new login account environment.

How to find the group names assigned to the user

The user can list of his active membership groups by running the linux command groups

The user can run the groups command to list the groups with active membership

[vamshi@linuxcent ~]$ groups
vamshi root wheel dockerroot

Login to the server remotely using SSH

You may now use the ssh command to login with the new username and enter your password at login prompt.

$ ssh [email protected]

How to connect to server with SSH running on non-standard port like 2202?

[vamshi@linuxcent ~]$ ssh localhost -p 2202
Last login: Mon Mar 13 17:57:56 2020 from 10.100.0.1

How to create a useraccount in Linux using useradd command?

The usercreation can also be done with parametrized command as demonstrated below:

$ sudo useradd vamshi -b /home/ -m -s /bin/bash

Alternatively you can be more elaborate as mentioned below:

$ sudo useradd vamshi -c "Vamshi's user account" -d /home/vamshi -m -s /bin/bash -G dockerroot

The useradd command-utility options describes as follows:

-b or --base-dir : base directory of new user home directory.

-c or --comment : Description about the user Or as A Standard Practice can be used to Mention the Current User’s Full name.

-d or --home-dir : create the user’s home directory

-m or --create-home :  create the user’s home directory as per -d option.

-s or --shell : Type of Login Shell.

-u or --uid : is the Unique UID on linux machine

-G or --groups : list of secondary groups to be assigned

-k or --skel : determines the default parameters if no options are passed while account creation. Present at /etc/default/useradd

With the skel properties finely tunes, you can proceed to use adduser command which is based on the default skel behavior as shown below:

$ sudo adduser vamshi

How to using the SSH key pair to login:
Use the -i followed by the /path/to/id_rsa private key file

$ ssh -i ~/.ssh/id_rsa [email protected]
$ ssh -i ~/.ssh/id_rsa -l linuxcent.com

-l : using the login name

-i : is the identity file; rsa the private key file

 

Troubleshooting the SSH connection in Verbose mode printing Debug information

Using -v option with the ssh command will print the debug information while logging

The verbosity levels -v can be concatenated from one to Nine; eg -v to -vvvvvvvvv

$ ssh -i ~/.ssh/id_rsa [email protected] -vvvvvvvvv

Linux Copy File Command for Files and Directories – cp Command Examples

Linux copy files command: cp is generally used for organizing the data on the Linux operating system, It copies the files and directories.

We shall take a deeper look at Linux cp command-utility in the section

In order to copy files and directories, you must have read permissions on the source file(s) and write permissions on the destination directory

How do I copy files under Linux operating systems?

How do I make a 2nd copy of a file on a Linux bash shell?

How can I copies files and directories on a Linux

Linux Copy File command Syntax

cp sourcefile destinationfile
cp sourcefile DESTDIR
cp sourcefile1 sourcefile2 DESTDIR
cp [OPTION] SOURCE DESTFILE
cp [OPTION] SOURCE DESTDIR

How to Copy a Directory if the destination does not exist?

To achieve this we can make use of the following cp command options -R or -r: Copy directories recursively.

Linux cp command Syntax with -R option:

cp -R SOURCE DESTINATION

If the destination doesn’t exist, it will be created.

It can also be used to Copy the contents Recursively

Lets see the demonstration as follows:

[vamshi@linuxcent ]$ cp -R dir1/ dir1-copy
[vamshi@linuxcent ]$ ls -l 
total 0
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:35 dir1
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:37 dir1-Recursive

Using the verbose Option -v to print the copy activity information onto the output screen.

Let’s use the -v flag to print the verbose information onto the screen.

How to Preserve the Source file and Directory permission?

Linux Copy command Syntax with -p option:

-p option preserves the mode, ownership and timestamps from the source to the destination

cp -p file1 file1-copy

Lets us see the Demonstration as Below

[vamshi@node02 cp-command]$ cp -Rp dir1/ dir1-copy
[vamshi@node02 cp-command]$ ls -ld dir1*
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:35 dir1
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:35 dir1-copy
drwxrwxr-x. 2 vamshi vamshi 6 Apr 11 06:37 dir1-Recursive

From the out we can conclude the the Linux copy command with -p Option preserves the original timestamps information and copies it to the destination

Linux cp command with Force copy -f Option, It forcefully overwrites the destination content
Sample Syntax:

cp -f file1 file1-copy

How to Copy Multiple files at once ?

Asterisk / wildcard (*) character is used to copy files multiple files with same pattern.

[vamshi@linuxcent ]$ cp -varpf file* DEST/
‘file10.txt’ -> ‘DEST/file10.txt’
‘file1.txt’ -> ‘DEST/file1.txt’
‘file2.txt’ -> ‘DEST/file2.txt’
‘file3.txt’ -> ‘DEST/file3.txt’
‘file4.txt’ -> ‘DEST/file4.txt’
‘file5.txt’ -> ‘DEST/file5.txt’
‘file6.txt’ -> ‘DEST/file6.txt’
‘file7.txt’ -> ‘DEST/file7.txt’
‘file8.txt’ -> ‘DEST/file8.txt’
‘file9.txt’ -> ‘DEST/file9.txt’

The options -p or -d enables preserving the links and can be used in conjunction with -R option to copy contents Recursively from the source directory.

How to Copy Files and Folders on Linux Using the cp Command recursively to Destination Directory

How to preserve the links with cp command?

Using the Options -p preserves the links and -r Option copies the content recussively same as -R Option and -v prints the verbose information

[vamshi@node02 Linux-blog]$ cp -varpf Redhat-Distro/ /tmp/DEST
‘Redhat-Distro/’ -> ‘/tmp/DEST’
‘Redhat-Distro/Fedora’ -> ‘/tmp/DEST/Fedora’
‘Redhat-Distro/Fedora/fedora.txt’ -> ‘/tmp/DEST/Fedora/fedora.txt’
‘Redhat-Distro/Centos’ -> ‘/tmp/DEST/Centos’
‘Redhat-Distro/Centos/centos.txt’ -> ‘/tmp/DEST/Centos/centos.txt’
‘Redhat-Distro/Centos/CentOS-versions’ -> ‘/tmp/DEST/Centos/CentOS-versions’
‘Redhat-Distro/Centos/CentOS-versions/centos7.txt’ -> ‘/tmp/DEST/Centos/CentOS-versions/centos7.txt’
‘Redhat-Distro/Centos/CentOS-versions/centos6.1.txt’ -> ‘/tmp/DEST/Centos/CentOS-versions/centos6.1.txt’
‘Redhat-Distro/Centos/README-CentOS’ -> ‘/tmp/DEST/Centos/README-CentOS’
‘Redhat-Distro/README-Redhat-Distro’ -> ‘/tmp/DEST/README-Redhat-Distro’
‘Redhat-Distro/RHEL-Versions’ -> ‘/tmp/DEST/RHEL-Versions’
‘Redhat-Distro/RHEL-Versions/redhat5.txt’ -> ‘/tmp/DEST/RHEL-Versions/redhat5.txt’
‘Redhat-Distro/RHEL-Versions/redhat8.txt’ -> ‘/tmp/DEST/RHEL-Versions/redhat8.txt’
‘Redhat-Distro/redhat.txt’ -> ‘/tmp/DEST/redhat.txt’

How to make a symbolic link with Linux cp command to files ?

As we know that ln command us useful to create symboic links, But the Linux copy command Syntax can do that to files with -s Option which creates Symbolic links:

cp -s SOURCE DESTINATION

Linux copy command Syntax with Softlink with Demonstration:

[vamshi@linuxcent ~]$ ls -l total 0
-rw-rw-r--. 1 vamshi vamshi 0 Apr 11 06:39 file1.txt

lrwxrwxrwx. 1 vamshi vamshi 9 Apr 11 06:39 file2.txt -> file1.txt

Linux cp command with interactive prompt using -i option

Sample Syntax:

cp -i file1 file1-copy

Also you can make it a best practice to setup alias alias for cp command.
The best practice is enable options -av

cp -av SOURCE DESTINATION
export cp="cp -av"

How can i copy the hidden files ?

To Copy the hidden files we can use cp command with -a option,lets us see in a practical example.

$ cp -av source/ destination/
‘source/.config1’ -> ‘destination/source/.config1’
‘source/.config2’ -> ‘destination/source/.config2’
‘source/.config3’ -> ‘destination/source/.config3’

Generally the hidden files in Linux are prefixed with a dot . So we can also use the wildcard character *, and copy them, below is another pracctical example

[vamshi@linuxcent cp-command]$ cp -av source/.conf* destination/
‘source/.config1’ -> ‘destination/.config1’
‘source/.config2’ -> ‘destination/.config2’
‘source/.config3’ -> ‘destination/.config3’

How to Copy a File from One Location to Another With a Different Name on Linux Using the cp Command

Assuming we have a couple of users on our linux server called Alice and Bob

[alice@linuxcent ~]$ sudo cp -avrpf /home/alice/djangoproject1/ /home/bob/
‘djangoproject1/’ -> ‘/home/bob/djangoproject1’
‘djangoproject1/__init__.py’ -> ‘/home/bob/djangoproject1/__init__.py’
‘djangoproject1/asgi.py’ -> ‘/home/bob/djangoproject1/asgi.py’
‘djangoproject1/settings.py’ -> ‘/home/bob/djangoproject1/settings.py’
‘djangoproject1/urls.py’ -> ‘/home/bob/djangoproject1/urls.py’
‘djangoproject1/wsgi.py’ -> ‘/home/bob/djangoproject1/wsgi.py’
‘djangoproject1/__pycache__’ -> ‘/home/bob/djangoproject1/__pycache__’
‘djangoproject1/__pycache__/__init__.cpython-36.pyc’ -> ‘/home/bob/djangoproject1/__pycache__/__init__.cpython-36.pyc’
‘djangoproject1/__pycache__/settings.cpython-36.pyc’ -> ‘/home/bob/djangoproject1/__pycache__/settings.cpython-36.pyc’

How to backup files using cp command?

The linux cp command offer the option --backup to backup the data files, below is the command.

cp --backup source destination

Best Linux Text Editors

Best Linux Text Editors

You can choose between several text editors in Linux. Each editor has advantages and advantages.

1. Vi/Vim
Vi is a powerful and the most popular command-line-based editor. Commonly used for writing code and editing configuration files. First of all, the advantage is availability. Vi is always installed on any distribution. The second advantage is the consumption of system resources. One of the cons is non-intuitive, but short commands.

Vi has 3 modes: command, input, and last line mode. Command mode is the default.

2. Nano
Nano is WYSIWYG (what you see is what you get) editor and is installed by default in Ubuntu and many other Linux distributions. Action/commands are done in a CTRL and Key manner, for example, CTRL + X save a file. Features: Autoconf support, case-sensitive search function, auto-indent ability, regular expression search and replace.

3. Gedit
Gedit is the default text editor for the GNOME desktop environment. Gedit’s aim is simple and easy to use for beginner Linux users. Useful features are syntax highlighting, clipboard support, brackets matching, search and replace with support of regular expressions

4. GNU Emacs
Emacs is the extensible self-documenting editor. It provides an interpreter for Emacs Lisp. Main function: text editing including a project planner, mail and newsreader, debugger interface, calendar.

5. Leaf Pad
GTK+ based editor is popular among new Linux users because it is easy to use. It supports the codeset option, auto codeset detection, and Drag & Drop function. It does not provide syntax coloring.

Which text editor is best Linux?

12 Best Text Editors For Linux Distros

  • Sublime Text. Sublime Text is a feature-packed text editor built for u201ccode, markup, and prose.u201d It natively supports tons of programming languages and markup languages. …
  • Atom. …
  • Vim. …
  • Gedit. …
  • GNU Emacs. …
  • Visual Studio Code. …
  • nano. …
  • KWrite.

What are the most common text editors in Linux?

Top 10 Text Editors for Linux Desktop

  • VIM. If you are bored of using the default u201cviu201d editor in linux and want to edit your text in an advanced text editor that is packed with powerful performance and lots of options, then vim is your best choice. …
  • Geany. …
  • Sublime Text Editor. …
  • Brackets. …
  • Gedit. …
  • Kate. …
  • Eclipse. …
  • Kwrite.

What text editor comes with Linux?

Almost all Linux distributions, even older versions, come with the Vim editor installed.

What is the best text editor 2020?

10 best code editors for 2020

  • Visual studio code. Visual studio code commonly referred to as VS code, is one of the best code editors in the market. …
  • Sublime text. If you are looking for a very lightweight yet robust code editor, the sublime text is your option. …
  • Atom Editor. …
  • Notepad++ …
  • Bluefish. …
  • Brackets. …
  • Phpstorm. …
  • GNU Emacs.

What text editor should I use for Linux?

There are two command-line text editors in Linuxxae: vim and nano. You can use one of these two available options should you ever need to write a script, edit a configuration file, create a virtual host, or jot down a quick note for yourself. These are but a few examples of what you can do with these tools.

What is the best text editor to use?

Best text editors in 2021: for Linux, Mac, and Windows coders and programmers

  • Sublime Text.
  • Atom.
  • Visual Studio Code.
  • Espresso.
  • Brackets.
  • Notepad++
  • Vim.
  • BBedit.

What is the best IDE for Linux in 2020?

10 Best IDEs For Linux In 2020!

  • NetBeans.
  • zend Studio.
  • Komodo IDE.
  • Anjuta.
  • MonoDevelop.
  • CodeLite.
  • KDevelop.
  • Geany.

Is VI the best text editor?

Vim is the best text editor/IDE out there. It is the x26quot;editor of choice of old-time Unix hackersx26quot;. Vim is one of the most popular programming editors out there. Itx26#39;s loved by geeks for its speed, extensive feature set, and flexibility.

Which text editor is used in Linux?

A Linux system supports multiple text editors. There are two types of text editors in Linux, which are given below: Command-line text editors such as Vi, nano, pico, and more. GUI text editors such as gedit (for Gnome), Kwrite, and more.

Which is the most common text editor?

The 15 Most Popular Text Editors for Developers

  • UltraEdit.
  • Dreamweaver.
  • Komodo Edit / Komodo IDE.
  • Aptana.
  • PSPad.
  • Vim.
  • TextMate.
  • Notepad++

How to manage LVM in Linux

How to manage LVM in Linux

Creating Dynamic Disc

We are going to create three discs on a USB drive, each disc will have 512 MB. First, verify if we have connected the USB drive as /dev/sdc/:

# fdisk -l

If we have a USB drive connected as /dev/sdc:

# fdisk /dev/sdc

Command d can remove existing logical volumes on the USB drive.

Enter commands n, p, 1-3, +512M to create 3 logical volumes. For example, we create the first volume /dev/sdc1:

Command (m for help): p
Command (m for help): n
Partition number (1-3): 1
First sector (34-41943006, default 41940992): 34
Last sector, +sectors or +size{K,M,G,T,P}: +512M
Command (m for help): p

Command w saves new partition table and changes can not be undone.

Reload partition table:

# partprobe

Format created discs:

# pvcreate /dev/sdc1
# pvcreate /dev/sdc2
# pvcreate /dev/sdc3

Verify:

# pvdisplay

Create volume group DATA:

# vgcreate DATA /dev/sdc1 /dev/sdc2 /dev/sdc3

To be sure verify group capacity:

# vgdisplay

Create physical volume from 100% of physical volume capacity.

# lvcreate -l +100%FREE -n new_volume DATA

Format the new volume:

# mkfs -t ext3 /dev/DATA/new_volume

Create a directory for mount:

# mkdir /mnt/dynamic

Mount the new volume:

# mount /dev/DATA/new_volume /mnt/dynamic

Mount verification:

# df -hT

Mount verification using a graphical interface:

# system-config-lvm

Dynamic Resize Dynamic Disk

Create primary logical partition /dev/sdc4, that use the rest of the USB drive:

# fdisk /dev/sdc
Command (m for help):n
Command (m for help):4
Command (m for help):p
<enter>
<enter>

Command w saves a new partition table and it can not be undone.

Verify partition table:

# partprobe

Add new disk to physical LVL partition:

# pvcreate /dev/sdc4

Verify:

# pvdisplay

Extend volume group:

# vgextend DATA /dev/sdc4

Verify extended volume group:

# vgdisplay

Extend logical volume with 1 GB:

# lvextend -L+1G /dev/DATA/new_volume

Resize size of disk:

# resize2fs /dev/DATA/new_volume

Remount:

# mount -o remount /dev/DATA/new_volume

Verify:

# df -hT

Removing Dynamic Disc

Unmount logical volume:

# umount /dev/DATA/new_volume

Remove logical volume:

# lvremove /dev/DATA/new_volume

Remove volume group:

# vgremove /dev/DATA

Remove physical volumes:

# pvremove /dev/sdc1
# pvremove /dev/sdc2
# pvremove /dev/sdc3
# pvremove /dev/sdc4

Verification using a graphical interface:

# system-config-lvm

Linux: How to Connect External Hard Drive

Linux: How to Connect External Hard Drive

Diagnostic Commands

Display from log directory what was recently connected

# tail -20 /var/log/messages

Display list of the partition tables

# fdisk -l

Display device parameters

# hdparm /dev/sda

More detailed information

# hwbrowser

# more /etc/sysconfig/hwconf

Connection Process

Run fdisk

# fdisk /dev/sda

Get list of existing partitions

Command (m for help): p

Delete partition which exist on the drive

Command (m for help): d

Create new partition

Command (m for help): n

Verification before save

Command (m for help): p

Save new table to drive

Command (m for help): w

Update partition table in system

# partprobe

Alternative to partprobe is hdparm -z

# hdparm -z /dev/sda

Format created partition to ext3 file system

# mkfs.ext3 /dev/sda1

Verification if the partition is not mounted

# df -hT

Mount new-created partition to directory /mnt/usb. If a directory does not exist, first created it.

# mkdir /mnt/usb

# mount /dev/sda1 /mnt/usb

# df -hT

Display disk partitions

# parted /dev/sda unit GB print free

Linux How to Generate Random Password

Linux How to Generate Random Password

Generating password is relatively simple and can be done in different ways. You can install tools to generate passwords, a few examples:

  • mkpasswd (Debian/Ubuntu)
  • makepasswd (Debian/Ubuntu)
  • pwgen (CentOS/Fedora/RHEL)

When you don’t have installed these tools, here are useful commands:

date +%s | sha256sum | base64 | head -c 32 ; echo

We used time in seconds as a input to hash function sha-256 and print first 32 chars. You can replate sha256sum with other hash function (md5sum).

strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 32 | tr -d '\n'; echo

/dev/urandom is the built-in feature which generate random chars.

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c32; echo

Another way using /dev/urandom, even simpler.

You can also create the script:

generatePasswd () {
local l=$1
[ "$l" == "" ] && l=16
tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}

generatePasswd "$1"