Author Archives: admin

How to Delete Lines in Vim / Vi

Vim comes out as an outstanding tool that helps to configure files and editing text mostly under Linux. One quirk of Vim that many cannot acknowledge is its capability to delete or erase complete lines in a text or file. Nothing complex about Vim but learning it is definitely useful.

Like every other work, deleting a line in Vim too has various methods. Vim, the widely known editor for text in Linux, can undo one or many patterns in a single command.

This tutorial will help you get knowledge on deleting lines by range or pattern by various options provided by Vim.

Various ways to delete a line in Vim

How to delete a single line?

  • Press on the Esc key and rapidly move along different files.
  • Move the cursor towards your line of choice for deleting.
  • If you want to delete a line, you need to press one of the following commands,
DD
D

Deleting a single word

  • Pressing Esc helps you enter the mode of command.
  • Next step involves the pointer being placed at the start of the very word.
  • Press down on the key that instant.

Steps for deleting multiple rows?

  • Start by pressing the Esc key.
  • Next step involves moving pointer to the line that’s needed to get deleted.
  • One use of one of the below mentioned commands the line will get deleted
[#]d d {# stands for no. of lines}
D-d-d

Method for deleting series’ of lines

  • Start by using the Esc key to enter a normal mode in Vim.
  • The following command will be brought to use with the beginning of the line’s range to the end of the line’s spectrum.

Example for reference is, deleting lines 3, 4, 5, and 6 by using the command: 2,6d.

Methodology for – delete all rows.

  • Firstly you press the Esc key.
  • Finally clear out everything inside the file by command, %d.
  • Once this command is executed, Vim will pop up, “No lines in buffer”.

Deleting the line present at the end of the file

Firstly the person needs to be moved to the line that needs deletion.
Entering command mode is followed by pressing of the Esc key.
The last step is to getting deleted every line except the ones you want to keep. The command needed: $d.

Deleting the line present at the beginning of the file

The first thing is to position the cursor properly on the line that needs deletion.
I am following with pressing the escape key.
Finally using the command delete the line at the beginning of the file.

Steps for deleting template-based lines

Vim allows you to get the lines with the coincidence of patterns. Many ways are available for deleting template-based lines. There are several ways to delete rows based on a template.

Deleting line laced with the specific word

  • Bring to use the Esc key and enter yourself into the mode of normality in the text.
  • You can delete the line with a specific word using, r / word/.

Getting lines lacking specific words deleted

  • Esc key will help you enter in command mode.
  • Use a particular command, r!/word/. To delete like lacking a specific word.

The process to delete the empty lines.

  • Blank lines can be deleted using the Esc key and switching to the normal mode.
  • Following above, enter the mentioned command will do the trick - r/^$/d

When does vim delete every line?

You get to delete a Vim/V line using: 1,$d. When you decide to delete all lines in vi go for: 1, here $ is symbolic of the line which is next in the command. Once a line starts with:g/^$/d it has the potential to delete all empty lines. ^$ present is the resemblance of the empty lines present. The command: g/^s/\*$/d, is capable of deleting every empty line present.

Conclusion

Once you have gone through the above article and have come to acknowledge the analysis well, you will have yourself many choices as to how you can delete a line or word on Vim.
Once you are well aware of Vim’s different commands, you will come to realise how time-efficient Vim will turn out to be.

How to Convert String into Integer in Python

Objects can be any kind of data type in Python, i.e. integer and string. Sometimes, you will need to convert one data form to another while writing Python code. For example, it needs to be transformed into an integer to perform a math operation on a number represented as a string. Here’s how to convert a string in Python to an integer.

int() function in Python

The built-in function int() returns an integer decimal object from a given number or String. It takes the form below:
int(a, base=10)

Two arguments are accepted by the function:

  • a – The number or String to be transformed to an integer.
  • base – Reflects the first argument’s numeral scheme. It can have a value between 0 and 2–36. It is optional to render this statement. The default base is always 10 if no base is defined (decimal integer). Integers are usually expressed in hexadecimal format i.e., base 16, decimal has base 10, octal has base 8, and binary has base 2.

If the given string cannot be interpreted as an integer, the ValueError exception is executed by the function.

Converting a String to Integer in Python

A ‘string’ is a list of characters declared in Python using a single (‘), double (“), or triple quotes (“””). If you use quotes to declare a variable that contains only numbers, its data type is set to String. Consider the instance below:

no_of_day = "23"
type(no_of_day)

The type() function tells us that the String object is the no_of_day variable.

<type 'str' > type

Let’s try on the variable to do a math operation:

print(day+5)

After that, Python throws an exception, i.e., TypeError, because it is unable to perform a string and integer addition calculation:

Traceback (last call last):
'' file, line 1, in
TypeError: can't concatenate items with 'str' and 'int.'

To convert a string representation of a decimal integer to an int, transfer a string that returns a decimal integer: to the int() function.

no_of_day = "23" days
no_of_day_int = int(no_of_day)
type(no_of_day_int)
<type 'int' >

The total operation will be done successfully if you try to do the math now:

print(no_of_day_int+5)
28

Remember, the commas you need to delete before passing the number to the int() function if the number contains commas, marking off thousands, millions, etc.:

total = "1,000,000"int(total.replace(",", ""))
1000000

When you execute the conversion between string to an integer, just make sure that you are using a correct base representing integers in various number systems. The number 54731 is expressed as D5CE in the hexadecimal method, for instance. You need to use Base 16 to convert it to a decimal integer:
If you move the D5CE String without setting the base to the int() function, the ValueError exception will be:

int ("D5CE", 16)
54731
Traceback (last call last):
'' file, line 1, in
ValueError: invalid literal with base 10 for int(): 'D5CF'

Conclusion:
In Python, using the int() function, you can convert a string to an integer.

How to Check whether a Directory or File Exists in Bash

Numerous scenarios will arise where you may need to perform an action based on whether a file exists or not.

While using the test command in Bash, you should determine whether a file exists and determine its file type.

A test command can take one of three possible syntax:

Test expression.

[ EXPRESSION ]

[[ EXPRESSION ]]

If you want a script to be portable, you should use the available command on all POSIX shells. The latest version of the test command, [[ (double brackets), is supported on most modern systems using the Bash, Zsh, and Ksh as a default shell.

Check if the file exists.

When checking a specific file, the most commonly used FILE operations include -e and -f. The first one will verify any file’s existence regardless of what type of file it is, while the second one will only return true for those files that are regular files (not a directory or a device).

The most efficient method of determining whether a file exists uses the test command and the if statement. Suppose you see any of the following, the /etc/resolv.conf file exists:

FILE=/etc/resolv.conf

if test -f "$FILE"; then

echo "$FILE exists."

fi
FILE=/etc/resolv.conf

if [ -f "$FILE" ]; then

echo "$FILE exists."

fi
FILE=/etc/resolv.conf

if [[ -f "$FILE" ]]; then

echo "$FILE exists."

fi

If you want to deliver a different action based on whether the file exists or not, simply use the if/then construct:

FILE=/etc/resolv.conf.

if [ "$FILE" ]; then

echo "$FILE exists."

else.

echo "$FILE does not exist."

fi

You can also operate a printer without the need for an if statement. The command following the && operator is only executed if the test command’s exit code is valid.

test -f /etc/resolv.conf && echo "$FILE exists."
[ -f /etc/resolv.conf ] && echo "$FILE exists."
[[ -f /etc/resolv.conf ]] && echo "$FILE exists."

When performing a series of commands using the && operator, make sure the semicolon does not separate them.

[ -f /etc/resolv.conf ] && { echo "$FILE exist."; cp "$FILE" /tmp/; }

What is said after the || operator is only valid as long as the test command’s exit status is false.

[ -f /etc/resolv.conf ] && echo "$FILE exist." || echo "$FILE does not exist."

Verify that Directory Exists.

The -d test tools you to quickly determine whether a file is a directory.

To check whether Docker’s /etc. The directory is present, use:

FILE=/etc/docker

if [ -d "$FILE" ]; then

echo "$FILE is a directory."

fi

[ -d /etc/docker ] && echo "$FILE is a directory."

Also, you can use the double brackets [[ instead of the single brackets [.

Check if the file already exists.

Moreover, the test expression can be negated using the word not. ! logical not operator:

FILE=/etc/docker

if not ( -f "$FILE" ]; then

echo "$FILE does not exist."

fi

Similar to above:

[ ! -f /etc/docker ] && echo "$FILE does not exist."

Check for multiple files.

Instead of using complex nested if/else statements, you can write a little more simply by using logic like this:

if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
echo "Both files exist."

fi

if [[ -f /etc/resolv.conf && -f /etc/hosts ]]; then

echo "Both files exist."

fi

Without using the IF statement:

[ -f /etc/resolv.conf -a -f /etc/hosts ] && echo "Both files exist."

[[ -f /etc/resolv.conf && -f /etc/hosts ]] && echo "Both files exist."

File test operators.

The test command includes some of the following file operators, which indicate whether a file is of a particular type.

  • -b FILE - True if that FILE exists and is also a special block file.
  • -c FILE - True if that FILE exists and is also a special character file.
  • -d source - True if source exists and is also a directory.
  • -e FILE - True if that FILE exists and is also a file, regardless of the type of (node, socket, directory, etc.).
  • -f FILE - True if that FILE exists and is also a regular file (not a device or directory).
  • -G FILE - True if that FILE exists and has the same group as the user is running that command.
  • -h FILE - True if that FILE exists and is also a symbolic link.
  • -g FILE - True if that FILE exists and also has set-group-id (sgid) flag set.
  • -k FILE – True if that FILE exists and also has a sticky bit flag set.
  • -L FILE – True if that FILE exists and is also a symbolic link.
  • -O FILE – True if that FILE exists and is also owned by the user running a command.
  • -p FILE – True if that FILE exists and is also a pipe.
  • -r FILE – True if that FILE exists and is also readable.
  • -S FILE – True if that FILE is also a socket.
  • -s FILE – True if that FILE exists and also has nonzero size.
  • -u FILE – True if that FILE exists, and also set-user-id (suid) flag is set.
  • -w FILE – True if that FILE exists and is also writable.
  • -x FILE – True if that FILE exists and is also executable.

How to Check Python Version

Python is one of the most successful programming languages in the world. It is used to develop websites, write scripts, machine learning, analyze data, and many more.

This article explains how to check what Python version is installed on your operating system working the command line. This can be beneficial when installing applications that require a particular version of python.

We will also explain to you how to programmatically determine what Python version is installed on the system where the Python script is running. For example, when writing Python scripts, you will require determining whether the script supports python’s version on the user’s machine.

Python Versioning

Python uses semantic versioning. Production-ready releases are versioned in the following scheme:

MAJOR.MINOR.MICRO

For example, in Python 3.6.8, 3 is a major version, 6 is a minor version, and 8 is a micro version.

  •  MAJOR – a python, has two major versions that are not fully cooperative: Python 2 and Python 3. For example, 3.5.7, 3.7.2, and 3.8.0 are all part of the Python 3 major version.
  • Minor: These announcements are bringing new features and roles. For example, 3.6.6, 3.6.7, and 3.6.8 are all part of the Python 3.6 minor version.
  • Micro: The new micro versions include various bug fixes and enhancements.

Development announcements have additional qualifiers. For more information, read the Python “Development Cycle” documentation.

Checking Python Version

Python is pre-installed on most maximum Linux distributions and macOS. On Windows, you have to download and install it if you want.

To get which version of python is fixed on your system, run the Python –version or Python -V command:

$ python --version

The order will print the default Python version, in this case, that is 2.5.15. The version installed on your system maybe another.

Output:

Python 2.7.15+

The default version of python will be applied by all scripts that have /usr/bin/python set as an interpreter in the script’s shebang line.

Some Linux distributions have various versions of python installed at the same time. The Python 3 binary is frequently named python3, and the Python 2 binary is called python or python2, but that may not always be the case.

You can check if you have Python 3 installed by typing:

$ python3 --version
Output:

Python 3.6.8

Python 2 support ended in 2020. Python 3 is the today and future of the programming language.

At the time of writing this article, the newest major release of python is version 3.8.x. The possibilities are that you can own an older version of Python 3 installed on your system.

If you want to install the most advanced python version, the method depends on your running system.

Programmatically Checking Python Version

Python 2 and Python 3 are different. The code written in Python 2.x may not work in Python 3.x, so you have to write two other codes.

The sys module that is open in all Python versions gives system-specific parameters and functions. sys.version_info enables you to discover the Python version installed on the system. It reflects a tuple that contains the five version numbers: major, minor, micro, release level, and serial.

Let’ say you have a script that needs at least Python version 3.5, and you want to tell whether the system meets requirements. You can do that by merely monitoring the major and minor versions:

import sys

if not (sys.version_info.major == 3 and sys.version_info.minor >= 5):

   print("This script requires Python 3.5 or higher!")

   print("You are using Python {}.{}.".format(sys.version_info.major, sys.version_info.minor))

   sys.exit(1)

If you run the script using Python version less than 3.5, it will produce the following output:

Output:

Python 3.5 or higher is required to run this script. 

You are using Python 2.5.

To write Python code that runs below both Python 3 and 2, use the future module. It enables you to run Python 3.x-compatible code below Python 2.

Conclusion: 

Using the python --version, it is very easy to find what version of python is installed on your system.

How to Change user password in Linux

This write-up is being provided to guide you through the procedure of changing your own user password in the application named Linux.

One interesting thing is that you can even forcefully make users change the password used for a login in Linux and that will be discussed here.

The procedural steps that are being provided here in this guide can also be used in other applications like Ubuntu, Debian, and CentOS.

Putting in the required changes in your already existing Password

If you wish to change the login details specifically the user password for your user login you will have to provide the command mentioned below with no other tit- bits following,

 $ passwd

Changing password for linuxize.

(Current) UNIX password:

Enter new UNIX password:

Retype new UNIX password:

passwd: password updated successfully

Once you put in the command $ password, a screen with the text mentioned above will pop up asking you the below-mentioned questions,

  • What is your current password?
  • What is the new password? Entering new password
  • Mention the new password again

Following the procedure above you will be easily able to bring the required changes in your user password.

Always remember that while filling the answers to the above questions you will not find them being showcased on the screen and front and that is totally normal.

Finally, when you try logging in to your system you will find that your new password has been generated and you can login using the freshly brewed user password.

How to facilitate change in password of another user?

It is not a factor to be surprised with as it has been already acquainted with you that access is granted to only the user who is rooted to the account or a user who has a sudo connection to the account will be provided the required privilege for making changes in the refreshed password for the account. The process that will be mentioned below is being mentioned keeping in mind that you are someone with the privilege of being connected to the account being handled as a sudo user.

When you are designing a change in a password for a different account you will have to type in the password command and entailing it should be the username of the account needing password changes. If we consider a password change in the account named lineux then the command followed will be,

$ sudo password lineux

Next step will be you coaxed into filling in a new password and confirming it:

Output

Enter new UNIX password:

Retype new UNIX password:

Once you are at the end of the procedure you will be faced with a command exactly like below,

Output

$ Password: password updated successfully

How can a user be pressured to change password at next login?

It has been set by default in many applications that the password set by a user for login details does not ever expire. Now a user can be pressurized to change the password when logging in for another time by undergoing a few commands while on the portal for Linux. The command that is provided for expiration of the old password is entailed by the name of the user:

$ sudo password --expire linuxize

Once you squeeze in the command mentioned above you will find the already existing password turning out to be immediately expired.

This procedure of immediate expiration of user’s earlier or old password will put pressure on the user to finally have the user password changed because of a message that will pop up when they log in again:

$ ssh linuxize@192.168.121.209
OUTPUT

WARNING: Your password has expired.

You must change your password now and login again!

Changing password for linuxize.

(Current) UNIX password:

Enter new UNIX password:

Retype new UNIX password:

password: password updated successfully

Connection to 192.168.121.209 closed.

You will see the connection being closed once the newly made and refreshed password is set by the user.

Conclusion

The write-up that was provided above was to help people with being able to bring out the required changes in their user password in a specific application named Linux.

The guidance that you got in the above right upper was how can you bring out the specific changes in the password and how can someone set an expiry limit to their password.

How to Add and Remove Users on Ubuntu 20.04

When provisioning a new Ubuntu system, the main task to be done is adding and removing users. Each user can have various permission levels and specific settings for different command-line and GUI applications.

So in this article, we have explained how to add and remove user accounts on Ubuntu 20.04

Before we start

Let us see some points.

Only root or users with sudo rights can create and remove users.

The following two ways are used to create new users:

  1. From the command line.
  2. Through the GUI.

Adding a User from the Command Line

In Ubuntu, there are a couple of command-line tools that you can do to create a new user account that is useradd and adduser.

useradd is a low-level utility. adduser is a script written in Perl that works as a friendly interactive frontend for useradd.

It is swift and easy to add a new user. Entreat the adduser command accompanied by the username. For example, to produce a new user account named username, you would work on the subsequent command

$ sudo adduser username
Output

Adding user `username '...

Adding new group `username' (1001) ...

Adding new user `username' (1001) with group `username' ...

Creating home directory `/home/username' ...

Copying files from `/etc/skel' ...

You will be examined a series of problems. Enter and validate the new user password. Answering all other questions is voluntary.

Output: 

Enter new UNIX password: 

Retype new UNIX password: 

passwd: password updated successfully

Changing the user information for username

Enter the new value, or press ENTER for the default

Full Name []: 

Room Number []: 

Work Phone []: 

Home Phone []: 

Other []: 

Is the information correct? [Y/n]

In the end, you will be required to confirm that the information you typed is accurate or not

The command will generate the new user’s home directory and copy files from /etc/skel to it. Inside the home directory, the user can write, edit, and delete files and directories which they want.

If you need the new user to be capable of performing administrative tasks, you require to add the user to the sudo group :

$ sudo usermod -aG sudo username

Adding a User through the GUI

If you are not satisfied with the command line, you can add a new user account through the GUI also. To do so, you will need to follow the steps given below:

  1. The first step is to open the settings window and click on the “Users” tab.
  2. Then you will need to click on the “Unlock” button and open your user password when mentioned.
  3. After you enter the password, the “Unlock” button will convert to a green “Add User” button.
  4. Then you will need to click on the “Add User” button, and then Add user dialog will arrive:
  5. Then you will need to select whether the new user should be a standard or administrator user and insert information. Once done, then you will need to click on the “Add” button.

Removing a User from the Command Line

The following two commands are used in Ubuntu to delete a user account: userdel and its interactive frontend deluser.

To delete the user, request the deluser command and pass the username as the argument:

$ sudo deluser username

The above command will not remove the user files.

If you need to delete the user and its home directory and mail spool, use the –remove-home flag command for a better result.

 Removing a User through the GUI

  1. The first step is to open the settings window and click on the “Users” tab.
  2. Then click on the “Unlock” button, and insert your user password when mentioned.
  3. Then click on the username which you want to delete, and you will observe a red “Remove User..” button on the base right corner, which indicated that the user could be removed.
  4. Then click the “Remove User..” button, and you will be mentioned whether to keep or delete the user home directory. By clicking on one of those buttons removes the user that you are willing to do.

Conclusion:

In this article, you have determined how to add and remove users in Ubuntu 20.04. Understanding how to add and remove users is one of the essential skills a Linux user should know.

How to Add and Delete Users on Ubuntu 18.04

Ubuntu is also a multi-user operating system like any other Linux distribution. Each user can have various permission levels and unique settings for different command-line and GUI applications.

Understanding how to add and remove users is one of the necessary skills a Linux user should know, as it is the primary task.

In this article, we will explain to you how to add and remove users on Ubuntu 18.04.

To be able to create and remove users, you require to be logged in as root or user with sudo perquisites.

How To Add User in Ubuntu

You can create a new user account in Ubuntu in two ways, which are as follows:

  1. From the command line.
  2. Through the GUI.

Add a New User from the Command Line

Two command-line tools can create a new user account that is useradd and adduser tool in Ubuntu.

Where useradd is used as a low-level utility for adding users, while the adduser a friendly interactive frontend to useradd written in Perl language.

To create a new user account named username using the adduser command, you would run:

$ sudo adduser username
Output:

Adding user `username'...

Adding new group `username' (1001) ...

Adding new user `username' (1001) with group `username' ...

Creating home directory `/home/username' ...

Copying files from `/etc/skel' ...

You will be asked a series of questions. The password is required, and all other fields are optional.

Output:

Enter new UNIX password: 

Retype new UNIX password: 

passwd: password updated successfully

Changing the user information for username

Enter the new value, or press ENTER for the default

Full Name []: 

Room Number []: 

Work Phone []: 

Home Phone []: 

Other []: 

Is the information correct? [Y/n]

Finally, if you want to confirm that the information is correct then enter Y.

The command will create the new user’s home directory, copy files from the/etc/skel directory to the user’s home directory. Within the home directory, the user can write, edit, and delete files and directories.

By default, on Ubuntu, members of the group sudo are granted with sudo access.

If you want the newly created user to have administrative rights, add the user to the sudo group :

 $ sudo usermod -aG sudo username

Add a New User through the GUI

If you are not satisfied with the command line, you can add a new user account through the GUI also. To do so, you will need to follow the steps given below:

  1. The first step is to search for “users” in the activation screen and then click on “Add or remove users and remember to change your password.”
  2. Then you will need to click on the “Unlock” button and open your user password when mentioned.
  3. After you enter the password, the “Unlock” button will convert to a green “Add User” button.
  4. Then you will need to click on the “Add User” button, and then Add user dialog will arrive:
  5. Then you will need to select whether the new user should be a standard or administrator user and insert information. Once done, then you will need to click on the “Add” button.

How To Delete a User

If the user account is no longer in use, then you can delete it each from the command line or GUI, whichever is preferred.

Delete a User from the Command Line

Two command-line tools can create a new user account that is userdel and deluser tool in Ubuntu. Where useradd is used as a low-level utility for adding users, while the adduser a friendly interactive frontend to useradd written in Perl language and it is more preferred to use.

To delete the user, without removing the user files, run:

$ sudo deluser username

The following command is used if you want to delete the user and its home directory and mail spool, use the –remove-home flag:

$ sudo deluser –remove-home username

Delete a User through the GUI

  1. The first step is to search for “users” in the activation screen and then click on “Add or remove users and remember to change your password.”
  2. Then click on the “Unlock” button, and insert your user password when mentioned.
  3. Then click on the username you want to delete, and you will observe a red “Remove User..” button on the base right corner, which indicated that the user could be removed.
  4. Then click the “Remove User..” button, and you will be mentioned whether to keep or delete the user home directory. By clicking on one of those buttons removes the user that you are willing to do.

Conclusion

In this article, you have learned how to add and remove users in Ubuntu. If you have any queries related to this topic, you can leave comments below.

How to Move Files and Directories in Linux with mv Command

Mv is one of the Linux commands that must be learned. Mv stands for transferring files or directories from one place to another and is primarily used for moving them.

The syntax is similar to the cp command in Linux, but there is a fundamental distinction between these two commands.

The cp command can be called a copy-paste method. The mv instruction, while the cut-paste process can be equivalent.

This means the file or directory is transferred to a different location using the mv command on a file or directory. The source file/directory is no longer there.

mv Command How can you use it?

The mv(transfer) command will move files and directories from place to place. It is also ideal for renaming files and folders.

mv [OPTIONS] source destination
  • The source may be a single file or directory in the above command. The destination is always a single file or directory.
  • When we have several files or folders, it is always a directory destination. Both source files and folders, in this case, are transferred to the directory of the destination. When we have a single source file and a destination directory, the file is transferred to the target folder.
  • One crucial point is that when we transfer files and folders, we will obtain permission refused if we don’t have written permissions both for the source and destination.

mv mv image.png PNG

The current working directory transfers the image.png file to the PNG folder in the current work directory.

The original filename is renamed as the destination file if the destination directory isn’t present.

The image.png file is called PNG if it is not present in the existing working directory.

Transfer several folders and files

Specify the files you want to transfer as the source to move several files and folders. For instance, you would type to transfer file1 and file2 to the directory dir1:

mv File1 File2 dir1

You can also use pattern matching with the mv button. For, e.g., you would like to transfer all pdf files to the ~/Documents directory from the existing directory:

mv *.pdf ~/Documents

Drag a folder inside a separate folder with the mv command
We may use the following command to transfer a directory within another directory:

mv mv abcd abcd_New

It passes the abcd directory to another abcd New directory in our existing working directory.
The source directory is reset to the destination directory if the destination directory is not present.

How to transfer several files to another directory:
All source files and the path to the target directory are defined to transfer several files within a different directory.

mv <source(source)file path 3>

Our current working directory transfers the files 1.jpg, 2.jpg, and 2.png into a separate image directory in the current working directory.

Within a directory, we can transfer multiple files using regular expressions that match the filenames to be transferred.

Mv *jpg JPG

All files with mv backup:
We use the -b option to back up current files. It is intended to create a backup of the overwritten ~ character file with the attached backup file name.

mv -b a.jpg 1.jpg

ls

File rename

The mv command is essential for file renaming. The source file shall be renamed to the target file if you are using an mv command and specify a file name in your destination.
mv source_file target directory/target file

Suppose the target file does not exist in the target directory. In that case, the target file will be generated in the above case.

However, it overwrites without asking if the target file already exists. This means that with the source file’s content, the content of the current target file will be modified.

OverRight file when moving:

The existing file contents would be automatically overridden if a file is transferred and there is already a file with the same name.

In all cases, this might not be optimal. The overwriting scenario is available in a variety of ways.
You may use the -n option to avoid overwriting existing files. So mv will not overwrite the current file.

mv -n source_file target_directory

Forced movement of the file:

If you are shielded from writing the target file, you will be required to check until the target file is overwritten.

mv file1.txt target
Mv: substitute 'target/file1.txt' for 0444 overriding (r—r—r—) mode?

You may use the force option -f to bypass this prompt and overwrite the file immediately.

mv -f File1.txt target

Fdisk Command in Linux (Create Disk Partitions)

Whenever you install a new SSD or hard disk, the first thing you have to do is to partition it. A drive requires to have at least one partition before you can format it and store files on it.

In Linux, there are many tools that you can use to generate partitions, with fdisk being the most usually used one.

In this article, let us see about the fdisk command.

fdisk is a menu-driven command-line utility that enables you to design and manipulate partition tables on a hard disk.

Be aware that fdisk is a severe tool and should be used with absolute caution. Only root or users with sudo privileges can manage the partition tables.

List Partitions

To list the partition table of a project, invoke the fdisk command with the -l option, followed by the device name. For example, to list the /dev/sda partition table and partitions, you would run:

$ fdisk -l /dev/sda

When no device is given as an argument, fdisk will print partition tables of all devices listed in the /proc/partitions file:

$ fdisk -l
Output:

Disk /dev/nvme0n1: 232.91 GiB, 250059350016 bytes, 488397168 sectors

Disk model: Samsung SSD 960 EVO 250GB

Units: sectors of 1 * 512 = 512 bytes

Sector size (logical/physical): 512 bytes / 512 bytes

I/O size (minimum/optimal): 512 bytes / 512 bytes

Disklabel type: gpt

Disk identifier: 6907D1B3-B3AB-7E43-AD20-0707A656A1B5

Device            Start       End   Sectors   Size Type

/dev/nvme0n1p1     2048   1050623   1048576   512M EFI System

/dev/nvme0n1p2  1050624  34605055  33554432    16G Linux swap

/dev/nvme0n1p3 34605056 488397134 453792079 216.4G Linux filesystem

Disk /dev/sda: 465.78 GiB, 500107862016 bytes, 976773168 sectors

Disk model: WDC WD5000AAKS-0

Units: sectors of 1 * 512 = 512 bytes

Sector size (logical/physical): 512 bytes / 512 bytes

I/O size (minimum/optimal): 512 bytes / 512 bytes

Disklabel type: dos

Disk identifier: 0x0001cca3

Device     Boot Start       End   Sectors   Size Id Type

/dev/sda1        2048 976771071 976769024 465.8G 83 Linux

The output over shows the current partition tables of all devices that are connected to your system. Generally, SATA device signs follow the pattern /dev/sd[a-z], while NVMe device signs have the following pattern /dev/nvme[1-9]n[1-9].

Creating Partition Table

To start partitioning the drive, run fdisk with the device name. In this example, we will work on /dev/sdb:

fdisk /dev/sdb

The command prompt will vary, and the fdisk dialogue where you can type in commands will open:

Welcome to fdisk (util-linux 2.34).

Corrections will remain in memory only until you decide to write them.

Be careful before using the write command.

Command (m for help):
Corrections you make to the partition table won't affect you until you write them with the w command. You can exit the fdisk dialogue without saving the changes using the q command.

To get a list of all available commands, enter m

(command m for help) m

Fdisk Command in Linux

If you are partitioning a new drive, you need to create a partition table before starting to create partitions. Skip this step if the device already has a partition table and you want to keep it.

fdisk supports several partitioning schemes. MBR and GPT are the two most popular partition scheme standards that store the partitioning information on a drive differently. GPT is a newer standard allowing and has many advantages over MBR. The main points to consider when choosing what partitioning standard to use:

  • Use MBR to boot the disk in legacy BIOS mode.
  • Use GPT to boot the disk in UEFI mode.
  • The MBR standard supports creating a disk partition up to 2 TiB. If you have a disk of 2 TiB or larger, use GPT.
  • MBR has a limit of 4 primary partitions. If you need more sections, one of the preceding sections can be set as an extended partition and hold additional logical partitions. With GPT, you can have up to 128 sections. GPT doesn’t support extended or logical partitions.

In this example, we will use a GPT partition table.

Enter g to create a new empty GPT partition table:

command (m for help) g

Output:

Created a new GPT disklabel (GUID: 4649EE36-3013-214E-961C-51A9187A7503).

The next step is to create the new partitions.

We will create two partitions. The first one with a size of 100 GiB, and the second one will take the rest of the disk space.

Run the n command to create a new partition:

command (m for help) n

You’ll be prompted to enter the partition number. Hit “Enter” to use the default value (1):

Partition number (1-128, default 1):

Next, the command will ask you to specify the first sector. Generally, it is always recommended to use the default values for the first value. Hit “Enter” to use the default value (2048):

First sector (2048-500118158, default 2048):

On the next prompt, you’ll need to enter the last sector. You can use an absolute value for the previous sector or relative importance to the start sector, using the + symbol following the partition size. The size can be specified in kibibytes (K), mebibytes (M), gibibytes (G), tebibytes (T), or pebibytes (P).

Enter +100G to set the partition size to 100 GiB:

Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-500118158, default 500118158): +100G
Output:

Created a new partition 1 of type' Linux filesystem' and size 100 GiB.

By default, the new partition type is set to “Linux filesystem,” which should be sufficient for most cases if you want to change the type, press l to get a list of partition types and then press t to change the style.

Let’s create the second partition that will take the rest of the disk space:

command (m for help) n
Partition number (2-128, default 2):

First sector (209717248-625142414, default 209717248):

Last sector, +/-sectors or +/-size{K,M,G,T,P} (209717248-625142414, default 625142414):

Once done creating partitions, use the p command to display the new partition table:

command (m for help) p

Disk /dev/sdb: 298.9 GiB, 320072933376 bytes, 625142448 sectors

Disk model: nal USB 3.0

Units: sectors of 1 * 512 = 512 bytes

Sector size (logical/physical): 512 bytes / 4096 bytes

I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disklabel type: gpt

Disk identifier: F8365250-AF58-F74E-B592-D56E3A5DEED1

Device Start End Sectors Size Type

/dev/sdb1 2048 209717247 209715200 100G Linux filesystem

/dev/sdb2 209717248 625142414 415425167 198.1G Linux filesystem
If you want to delete a partition, use the d command.

Save the changes by running the w command:

command (m for help) p

The command will write the table to disk and exit the fdisk menu.

Output:

The partition table has been altered.

Calling ioctl() to re-read partition table.

Syncing disks.

The kernel will read the device partition table without the need to reboot the system.

Activating the Partitions

Now that the partitions have been created, the next step is to format the partitions and mount them to the system’s directory tree.

We’ll format both partitions to ext4:

sudo mkfs.ext4 -F /dev/sdb1sudo mkfs.ext4 -F /dev/sdb2

mke2fs 1.45.5 (07-Jan-2020)

Creating filesystem with 51928145 4k blocks and 12984320 inodes

Filesystem UUID: 63a3457e-c3a1-43f4-a0e6-01a7dbe7dfed

Superblock backups stored on blocks:

32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,

4096000, 7962624, 11239424, 20480000, 23887872

Allocating group tables: done

Writing inode tables: done

Creating journal (262144 blocks): done

Writing superblocks and filesystem accounting information: done

We will mount the partitions to /mnt/audio and /mnt/video directories in this example.

Create the mount points with mkdir :

sudo mkdir -p /mnt/audio /mnt/video

Mount the new partition:

sudo mount /dev/sdb1 /mnt/audio
sudo mount /dev/sdb2 /mnt/video

Partitions will stay mounted until you unmount it or shut down the machine. To automatically mount a partition when your Linux system starts up, define the mount in the /etc/fstab file.

That’s it! You can now use the new partitions to store your files.
Conclusion
fdisk is a command-line tool for creating partition schemes. For more information about the fdisk command, type man fdisk in your terminal.

Chown Command in Linux (File Ownership)

If you want to change the user and/or group ownership of a given file, directory, or symbolic link, the chown command is used. So in this article, we will show you how to use the chown command through practical examples.

Let us see How to Use chown.

Before moving into how to use the chown command, let’s begin by examining the basic syntax.

The chown command expressions take the subsequent form:

chown [OPTIONS] USER[:GROUP] FILE(s)

USER is nothing but the user name or the user ID (UID) of the new owner. The name of the group ID (GID) or the new group is GROUP. The name of one or more directories, files, or links is FILE(s). Remember, always numeric IDs should be prefixed with the + symbol.

  • USER – If only the user is defined, the defined user will grow the given file owner, the group ownership is not changed.
  • USER: – When the username is succeeded by a colon: and the group name is not given, the user will become the owner of the files, and the files group ownership is transferred to the user’s login group.
  • USER: GROUP – If both the group and the user are defined (with no space between them), the user ownership of the files is transferred to the given user, and the group ownership is transferred to the given group.
  • GROUP – If the User is canceled and the group is prefixed with a colon, only the files’ group ownership is transferred to the given group.
  • : If only a colon: is given, without defining the user and the group, no change is made in it.

By default, on success, chown doesn’t give any output and returns zero.

To find out who holds a file or what group the file refers to, use the ls -l command:

$ ls -l filename.txt
Output:

-rw-r--r-- 12 linuxize users 12.0K Apr 8 20:51 filename.txt

Regular users can replace the filegroup only if they own the file and only to a group they are a member of. Administrative users can replace the group ownership of all files.

How to Replace the Owner of a File

If you want to replace the owner of a file, then use the chown command succeeded by the user name of the new owner and the target file as an argument:

chown USER FILE

For example, the subsequent command will transfer the ownership of a file named file1 to a new owner named linuxize:

$ chown linuxize file1

To transfer the ownership of multiple files or directories, define them as a space-separated list. The command below turns the ownership of a file named file1 and directory dir1 to a new owner named linuxize:

$ chown linuxize file1 dir1

For example, the subsequent command will transfer the ownership of a file named file1 to a new owner named linuxize:

$ chown linuxize file1

To transfer the ownership of multiple files or directories, specify them as a space-separated list. The command following transfers the ownership of a directory with name dir1 and a file with name file1 to a new owner named linuxize:

$ chown linuxize file1 dir1

The alternatively used for the username is the numeric user ID (UID). The following example will transfer the ownership of a file named file2 to a new owner with a UID of 1000:

$ chown 1000 file2

If a numeric owner survives as a user name, then the ownership will be transferred to the user name. To bypass this, prefix the ID with +:

$ chown 1000 file2

How to Replace the Owner and Group of a File

If you want to replace both the owner and the group of a file, use the chown command supported by the new owner and group separated by a colon (:) with no intermediary spaces and the target file.

$ chown USER: GROUP FILE

The subsequent command will transfer the ownership of a file named file1 to a new owner named linuxize and group users:

$ chown linuxize: users file1

If you cancel the group name after the colon (:) the group of the file is replaced to the specified user’s login group:chown linuxize: file1

How to Replace the Group of a File

To replace only the group of a file, use the chown command followed by a colon (:) and the new group name (with no space between them) and the target file as an argument:

$ chown: GROUP FILE

The subsequent command will replace the owning group of a file named file1 to www-data:

$ chown :www-data file1

Another command that you can use to replace the group ownership of files is chgrp.

How to Replace Symbolic Links Ownership

When the recursive alternative is not used, the chown command replaces the group ownership of the files to which the symlinks point, not the symbolic links themselves.

For example, if you try to replace the owner and the group of the symbolic link symlink1 that points to /var/www/file1, chown will change the ownership of the file or directory the symlink points to:

$ chown www-data: symlink1

The possibilities are that instead of changing the target ownership, you will get an error “cannot dereference ‘symlink1’: Permission denied”.

The error happens because, by default on most Linux distributions, symlinks are protected, and you cannot work on target files. This option is defined in /proc/sys/fs/protected_symlinks. One means enabled, and zero means disabled. We suggest not to disable the symlink protection.

To replace the group ownership of the symlink itself, use the -h option:

$ chown -h www-data symlink1

How to Recursively Replace the File Ownership

To recursively run on all files and directories under the given directory, use the -R (–recursive) alternative:

$ chown -R USER: GROUP DIRECTORY

The following example will transfer the ownership of all files and subdirectories under the /var/www directory to a new owner and group named www-data:

$ chown -R www-data: /var/www

If the directory contains symbolic links, pass the -h option:

$ chown -hR www-data: /var/www

Other alternatives that can be used when recursively replacing the directory ownership are -H and -L.

If the argument passed to the chown command is a symbolic link pointing to a directory, the -H option will create the command to cross it. -L tells chown to cross each symbolic link to a guide that is found. Usually, it would be best to use these choices because you might mess up your system or perform a security risk.

Using a Reference File

The -- reference = ref_file option enables you to change the user and group ownership of given files to be the same as those of the detailed reference file (ref_file). Chown will use the target file user and group; if the reference file is a symbolic link.

$ chown --reference=REF_FILE FILE

For instance, the subsequent command will allow the user and group ownership of the file1 to file2

$ chown --reference=file1 file2

Conclusion

The chown is a Linux/UNIX command-line service for developing the file’s user and/or group ownership.

To discover more about the chown command, visit the chown man page or type man chown in your terminal. If you have any questions or feedback, please leave a comment below or contact us directly.