Linux – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 30 Jan 2024 09:00:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Linux – Java2Blog https://java2blog.com 32 32 Resolve Device or Resource is Busy Error in Linux https://java2blog.com/resolve-device-or-resource-is-busy-error-linux/?utm_source=rss&utm_medium=rss&utm_campaign=resolve-device-or-resource-is-busy-error-linux https://java2blog.com/resolve-device-or-resource-is-busy-error-linux/#respond Thu, 04 May 2023 04:24:05 +0000 https://java2blog.com/?p=23591 1. Introduction

When working with Linux, you might encounter the error message “Device or Resource is Busy” while trying to unmount a filesystem, detach a storage device, or perform operations on files or directories. This error indicates that the target you’re trying to operate on is currently in use by the system or a process, preventing your intended action.

Our goal is to effectively resolve this error, ensuring that we can safely proceed with operations such as unmounting a filesystem, deleting a file, or detaching a storage device without causing system instability or data loss.

2. Understanding the Error

Before diving into solutions, let’s understand why this error occurs. Linux, being a multi-user, multitasking system, allows multiple processes to access files and devices simultaneously. When a device or file is being accessed (read or written to) by a process, Linux locks it to prevent data corruption. Attempting an operation that requires exclusive access to a locked resource triggers the “Device or Resource is Busy” error.

3. Identifying the Cause

To resolve the error, the first step is identifying which process is holding onto the device or file. We’ll use the lsof and fuser commands for this purpose.

3.1 Using lsof (List Open Files)

lsof is a powerful utility that lists information about files opened by processes. To find out which process is using a specific file or device, we can use:

lsof +D /path/to/device_or_file

Using +D is particularly useful when we suspect that a file causing the “Device or Resource is Busy” error might not be directly within the top level of a given directory but rather nested within its subdirectories. This option ensures that no stone is left unturned in our search for the open file causing the issue.

Example:

If we’re trying to unmount a USB drive mounted at /media/usb and encounter the error, we can run:

lsof +D /media/usbOutput:

COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
bash    54321 user   cwd    DIR   8,16     4096    2 /media/usb

This output tells us that a bash process with PID 54321 is using the USB drive.

3.2 Using fuser

fuser identifies processes using files or sockets. To check which process is accessing a mount point or device, use:

fuser -vm /path/to/mount_point

Example:

Again, for the USB drive scenario:

fuser -vm /media/usb

Output:

USER        PID ACCESS COMMAND
/media/usb:
            user     54321 ..c.. bash

This indicates the same bash process with PID 54321 is accessing the USB drive.

4. Resolving the Error

Once the offending process is identified, we have several options to resolve the issue:

4.1 Safely Closing the Process

If the process is a user application, you might simply close it from its GUI or terminate it gently using:

kill PID

Replace PID with the actual process ID. For our example, it would be kill 54321.

4.2 Forcefully Killing the Process

If the process does not respond, use the -9 option to forcefully kill it:

kill -9 PID

Replace PID with the actual process ID. For our example, it would be kill -9 54321.

Always be careful while using the kill command because it may cause system instability or data loss if not used correctly.

4.3 Unmounting with the unmount Command

If the resource is a filesystem, you can try to unmount it using:

umount -l /path/to/mount_point

The -l option lazily unmounts the filesystem, detaching it as soon as it’s not busy anymore.

4.4 Automating with a Script

For recurring issues, we might consider writing a simple bash script that uses lsof or fuser to find and terminate the offending process before performing the desired operation. Below solution will help us to automate with the script.

5. Using lsof, awk and kill Together [One Liner]

In addition to the detailed approaches mentioned earlier, there’s an efficient one-liner command that combines the power of lsof, awk, and kill to swiftly resolve the “Device or Resource is Busy” error. This method is particularly useful when we need a quick resolution without manually identifying and terminating each process.

To harness this method, we utilize the lsof command to list open files in a directory, awk to filter out the process IDs, and kill to terminate these processes. Here’s the command:

lsof +D /path/to/directory | awk '{print $2}' | tail -n +2 | xargs -r kill -9

Let’s break down this command for better understanding:

  1. lsof +D /path/to/directory: This part of the command uses lsof to list all open files within a directory and its subdirectories. Replace /path/to/directory with the actual path where the resource or device is busy.
  2. awk '{print $2}': awk processes the output of lsof, extracting the second column which contains the process IDs (PIDs).
  3. tail -n +2: This command skips the first line of the output, which is usually the header containing column titles like “COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME”.
  4. xargs -r kill -9: Finally, xargs takes the list of PIDs and passes them to kill -9, forcefully terminating each process. The -r option prevents kill from running if there are no inputs, avoiding unnecessary errors.

5.1 Caution and Consideration

While this one-liner is highly effective, it’s important to use it with caution. Forcefully killing processes with kill -9 can lead to data loss or instability, especially if the processes are critical to system or application functionality. Always ensure that the directory specified in the command is the one you intend to target, and consider the implications of abruptly stopping the identified processes.

6. Conclusion

The “Device or Resource is Busy” error in Linux signals that a file or device is under use by a process, hindering our intended operations. By leveraging tools like lsof and fuser, we can pinpoint and manage these processes, ensuring the smooth execution of our tasks. It’s imperative to approach such situations with caution to avert potential data loss or system instability, especially when forcibly ending processes or unmounting filesystems.

]]>
https://java2blog.com/resolve-device-or-resource-is-busy-error-linux/feed/ 0
What is awk print $2 https://java2blog.com/awk-print-2/?utm_source=rss&utm_medium=rss&utm_campaign=awk-print-2 https://java2blog.com/awk-print-2/#respond Thu, 05 Jan 2023 13:19:06 +0000 https://java2blog.com/?p=22336 In this tutorial, we will see about what is meant by awk print $2.

awk is interpreted programming language. It is very powerful programming language and used for text processing. Awk stands for the names of its authors “Aho, Weinberger, and Kernighan”.

awk print $2

As said before, awk can be used for text processing. awk treats tab or whitespace for file separator by default.
Awk actually uses some variables for each data field found.

  • $0 for whole line
  • $1 for first field
  • $2 for second field
  • $3 for third field
  • $n for nth field

so, here awk print $2 represents second field in the file.

Let’s understand with the help of an example.

$ cat > sample.txt

This is sample file
Java is programming language.
This is Java tutorial
I know Java very well.

Let’s run the command now

$awk ‘{print $2}’ sample.txt

is
is
is
know

If you notice awk print $2 prints second word of each line.
If you use $3, it will print 3rd word of each line.

$awk ‘{print $3}’ sample.txt

sample
programming
Java
Java

Let’s use csv file now for demonstration

$ cat > countries.csv

#Country,Population,Captital
India,10000,Delhi
Nepal,2000,Kathmandu
China,20000,Beijing

Let’s print second column of csv file using awk print $2 command. We need to provide explicit delimeter over here.

$awk -F’,’ ‘{print $2}’ countries.csv

Population
10000
2000
20000

That’s all about awk print $2 command.

]]>
https://java2blog.com/awk-print-2/feed/ 0
Sed Command in unix https://java2blog.com/sed-command-unix/?utm_source=rss&utm_medium=rss&utm_campaign=sed-command-unix https://java2blog.com/sed-command-unix/#comments Fri, 18 Jan 2019 17:16:26 +0000 https://java2blog.com/?p=6953 Sed (Stands for stream editor) is a command line utility to modify each line of a file or stream matching a specified string. It makes basic text changes to a file or input from a pipeline.

Sed command can perform variety of functions on file like, searching, find and replace, insertion or deletion. Most common use of Sed command is for substitution or to find and replace. With SED command, you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in Editor and then changing it.

An example can help understanding the Sed command. We have a file named sed_demo.txt having these lines.

$ cat sed_demo.txt >
1. Nike Shoes – Tag 344 – Price $ 16
2. Rebook shoes – Tag 433 – Price $ 17
3. Bata Shoes – Tag 211 – Price $ 18
4. Summer Shoes – Tag 978 – Price $ 16

We want to change the price of $ 16 with $ 19. Sed command allows us to do that

$ sed ‘s/16/19/’ sed_demo.txt

On execution of above command you will see something like this

$ cat sed_demo.txt
1. Nike Shoes – Tag 344 – Price $ 19
2. Rebook shoes – Tag 433 – Price $ 17
3. Bata Shoes – Tag 211 – Price $ 18
4. Summer Shoes – Tag 978 – Price $ 19

If we want to change in file, then use below command, use below command.

$ sed -i -e ‘s/16/19/’ sed_demo.txt

Price of Nike Shoes and Summer Shoes are now increased to $ 19 (shown in bold).

Here is another way of doing this

$ sed ‘s/16/19/’ sed_demo.txt > sed_demo_new.txt

this command will also change price of Nike Shoes and Summer Shoes to 19 but changes are saved it in a new file with name sed_demo_new.txt, in this case original file sed_demo.txt remains unaffected.

With sed command you can extract lines having specific string.

$ sed -n ‘/Bata/p’ sed_demo.txt > sed_demo_new.txt

this will extract all lines having ‘Bata’ and paste it into a new file named sed_demo_new.txt.

You can apply sed command to STDIN also like this,

$ echo ‘Welcome to My Linux Blog’ | sed ‘s/Blog/website/’

The s option replaces the first text with the second text pattern. In this case, the string "Blog" will be replaced with "website". Output of this command will be

Welcome to My Linux website

Sed command has /1, /2 etc flags that can replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word "shoes" with "shirt" in a line.

$ sed ‘s/shoes/Shirt/2’ sed_demo.txt

Sed command has substitute flag /g (global replacement) that replaces all the occurrences of the string in the line.

$ sed ‘s/shoes/Shirt/g’ sed_demo.txt

This will replace every occurrence of shoes with shirt in sed_demo.txt file.

You can also combine /1, /2 etc with /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the second onward occurrence of "shoes" word with "Shirt" word in a line.

$ sed ‘s/shoes/Shirt/2g’ sed_demo.txt

To learn more on Sed command type $ man Sed on your unix distribution.

That’s all about Sed command in unix.

]]>
https://java2blog.com/sed-command-unix/feed/ 1
Find command in linux https://java2blog.com/find-command-linux/?utm_source=rss&utm_medium=rss&utm_campaign=find-command-linux https://java2blog.com/find-command-linux/#respond Tue, 16 Oct 2018 18:17:27 +0000 https://java2blog.com/?p=6608 In this post, we will see about find command in linux.
Find is an important and one of most widely used command in Unix and Linux operating systems. It is used to search and locate list of files and directories based on conditions you specify for files that match the arguments.

Find command lets you search used in variety of conditions like you can search files by permissions, users, groups, file type, date, size and other possible criteria. Searching by Find command is recursive in a sense that it will search subdirectories as well.


Syntax

$ find [path] [search criteria] [action]

all these options following the Find command are optional, let’s see how

If you type $ find and press enter it will display the pathnames of all files in the current directory and all subdirectories. Same will happen if you type $ find . and press enter.

If you want to search for file named arpit in current directory, use this

$ find / -name arpit

You can also do this by using

$ find . -name arpit

find command by default is case sensitive, if you want to search without case sensitivity

$ find / -iname arpit

this will search for files that match arpit, ARPIT, Arpit and all other combination in current directory.


Searching for Files and Directories Only

You can also search files or directories only using -type option. To find files with name arpit use

$ find -type f -name arpit

To find directories with name arpit use

$ find -type d -name arpit

This will search for only files with name arpit in current and sub-directories removing case sensitivity filter.

$ find / -type f -iname arpit

You can also use wild cards with find command. For instance

$ find / -type f -iname “*.txt”

this will search current and sub-directories for files with .txt extension.


Search based on File Permission

With find command you can also search files based on specific permission. For instance

$ find -perm 777

This will display all files with permission 777 in your current directory.


Search for files that are modified at some specific time/day

If you want to search for files that are modified in last one day using mtime

$ find . -mtime +1

If you want to search for files that are modified in last one min

$find . -mmin +1

if you want to search for files that are modified more then 2 and less than 5 min

$ find . -mmin +2 -mmin -5

Search based on User

If you want to search for files of user arpit in the current and sub-directories, use this

$ find / -user arpit -iname “*.txt”

Search based on File size

To find all files of size 10MB , use.

$ find / -size 10M

You can also find and delete 50MB files and delete them in one single command

$ find / -size +50M -exec rm -rf {} \;

To learn more about Find command, type $ man find on your Linux terminal

That’s all about Find command in linux.

]]>
https://java2blog.com/find-command-linux/feed/ 0
Grep command in unix https://java2blog.com/grep-command-unix/?utm_source=rss&utm_medium=rss&utm_campaign=grep-command-unix https://java2blog.com/grep-command-unix/#respond Mon, 15 Oct 2018 16:09:52 +0000 https://java2blog.com/?p=6577 In this post, we will see about grep command in unix.
The grep command stands for "Global Regular Expression Print" and is used to search text or searches the given file for lines containing a match to the given strings or words. It is a powerful file pattern searcher in Linux and Unix-like operating systems. Let’s see how it can be used.


Syntax

$ grep [OPTIONS] PATTERN [FILE…]

Installing grep<

To install grep on Debain based distributions, use following command

$ sudo apt-get install grep

For Redhat, CentOS and Fedora distributions

$ sudo yum install grep

Working with Grep

If you want to search user arpit in /var.logs.application.log file, use the following command.

$ grep arpit /var/logs/application.log

Output will be all lines in application.log file matching the string arpit. On my system output of above command is

$grep arpit /var/logs/application.log

arpit:x:1000:1000:arpit,,,:/home/arpit:/bin/bash

Output of grep will be blank in case nothing match the search string.

Grep command is case sensitive. If you want to work without case sensitivity, use -i option

$ grep -i arpit /var/logs/application.log

this will display all lines that match arpit, ARPIT, Arpit and all other combinations.

You can also search string in multiple files.

$ grep -i arpit application.log applicationBackup1.logapplicationBackup2.log

the above command will search arpit in application.log applicationBackup1.logapplicationBackup2.log files.

If you want to search every file in your current directory with a string.

$ grep arpit *

this will search every file in current directory with string arpit.

To get name of all files having a specific string.

$ grep -l arpit *

If string contains spaces, enclose it in double quotes

$ grep -i “Arpit Blog” *

To highlight the successful matches, use the —color option

$ grep –color arpit application.log

If you want to get line numbers where string is found

$ grep -n arpit application.log

Grep command allows you to search in subdirectories using -r option. -r tells grep to perform its search recursively.

$ grep -r arpit /etc/

this will read all files under each directory for a string arpit.

By default, grep displays the entire line having the matched string. If you want to display only the matched string, use -o option

$ grep -o arpit application.log

Working with Grep


Using Grep with other commands

You can also use grep command in combination with other command by using pipeline ( | ) symbol. This option is very handy.

$ ls /usr/bin | grep zip

grep will read all files residing in /usr/bin directory and will display files whose filename contains string zip.

$ ls /usr/bin | grep -v zip

this will print all the file names that don’t have string zip. This is just like applying not operator to grep command.

$ ls /usr/bin | grep -c zip

above command will give the number of files having string zip.

$ ls /usr/bin | grep -cv zip

this will give no of files that don’t have string zip.

This tutorial shows few cases of how grep command can be used, there are many more also. To learn more on grep please type $ man grep on your unix terminal.

That’s all about Grep command in unix.

]]>
https://java2blog.com/grep-command-unix/feed/ 0
What is awk print $1? https://java2blog.com/awk-print-1/?utm_source=rss&utm_medium=rss&utm_campaign=awk-print-1 https://java2blog.com/awk-print-1/#respond Wed, 26 Sep 2018 16:43:45 +0000 https://java2blog.com/?p=6553 1. Introduction

awk is interpreted programming language. It is very powerful and used for text processing. Awk stands for the names of its authors “Aho, Weinberger, and Kernighan”.

One of its fundamental features is the ability to easily extract specific columns from a text input. The command awk print $1 is used for this purpose. It prints the first field (or column) from each line of a given input.

2. Understanding awk print $1

The awk print $1 command is used to extract the first column(or field) of data from a text input.

Let’s see with the help of example:

echo "Hello world from Java2blog" | awk '{print $1}'

Hello

  • awk '{print $1}' tells awk to execute the print action, where $1 refers to the first field (or column) of the input.
  • By default, awk considers spaces and tabs as field separators.

Awk actually uses some variables for each data field found as below:

So here, print $1 represents the first field of the input.

3. Changing the Field Separator

In scenarios where data is not space-delimited, we can provide custom delimiter with -F flag.

Let’s understand with the help of an example:

echo "India, China, Bhutan, Russia" | awk -F',' '{print $1}'

India

-F',' sets the field separator to a comma, and $1 then refers to the data before the first comma.

4. Printing Multiple Fields

To print multiple fields, we can include multiple field identifiers in the print action.

echo "India, China, Bhutan, Russia" | awk -F',' '{print $1, $4}'

India Russia

{print $1, $4} prints first and fourth fields.

5. Using awk print $1 with Files

awk command can process file input directly, making it easier to use it with files.

Let’s read a csv file and prints its first column:

awk -F',' '{print $1}' countries.csv

This prints first field of each line of comma delimited csv file.

6. Combining awk with Other Commands

In practice, awk is often combined with different other commands to get desired output.
Here is one example of such command:

cat file.txt | awk '{print $1}' | sort | uniq

This commands extracts first field of file.txt, sort it, and filter out duplicate values.

7. Conclusion

awk print $1 is a fundamental command in text processing for Unix and Linux users. It’s simple yet powerful, capable of handling a wide range of data extraction tasks.

By changing the field separator and combining awk with other commands, you can manipulate and extract data from text inputs effectively. Whether you’re dealing with log files, CSVs, or any structured text data, awk print $1 and its variations offer a versatile solution for your scripting needs.

]]>
https://java2blog.com/awk-print-1/feed/ 0
sed Replace String in File https://java2blog.com/sed-replace-string-file/?utm_source=rss&utm_medium=rss&utm_campaign=sed-replace-string-file https://java2blog.com/sed-replace-string-file/#respond Sun, 23 Sep 2018 18:40:23 +0000 https://java2blog.com/?p=6487 In this post, we will see how to replace String in file using sed in linux.

Problem

How to find and replace "Text1" with "Text2" using sed command in linux.

Solution

Sed stands for stream editor.It reads the file and modifies the file as provided by list of sed command.By default, input is written on the screen but you can update the file as well using -i option.

Here is simple command to replace string in file.

sed -i -e ‘s/old-string/new-string/g’ sample.txt

]]>
https://java2blog.com/sed-replace-string-file/feed/ 0
Find file containing text in linux https://java2blog.com/linux-find-file-containing-text/?utm_source=rss&utm_medium=rss&utm_campaign=linux-find-file-containing-text https://java2blog.com/linux-find-file-containing-text/#respond Sun, 23 Sep 2018 18:37:00 +0000 https://java2blog.com/?p=6512 In this post, we will see how to find files containing specific text.

Problem

You want to search for any specific text in all the files in a directory.

Solution

There are lots and lots of files on linux or unix server. You can find and locate a file using find command but it is not possible to look inside a text file for specific text.

You can use grep command. Grep command searches given inputs files for line containing specified text.


1. Search text "https://www.google.com" in current directory

grep -s “text to be searched” *

Run example:

$ grep -s “https://www.google.com” *

site.txt:https://www.google.com is awesome search engine


2. Search text "https://www.google.com" in current directory and all subdirectories

grep -r “https://www.google.com” *

3. Search text "https://www.google.com" in current directory,all subdirectories and display matched text in color

grep -r –color “https://www.google.com” *

4. Search text "https://www.google.com" in /opt directory and display just file name

By default, grep prints file name and line containing text in a file. If you just want to display file name, you can use below command.

grep -r “https://www.google.com” /opt/*| cut -d: -f1

5. Hide warning spam

By default, grep prints file name and line containing text in a file. If you just want to display file name, you can use below grep command generates lots of error message due to permission issues such as

No such file or directory
No such device or address
Permission denied

Sometimes, you get so many errors that it is hard to find actual file.To hide all error or warning message, append 2>/dev/null to grep command. This will send and hide unwanted outut to /dev/null.

grep -r “https://www.google.com” /opt/* 2>/dev/null

6. Ignore case while searching text

If you want to do case insensitive search, then use -i option with grep.

grep -r -i “https://www.google.com” *

That’s all about how to find file containing text in linux

]]>
https://java2blog.com/linux-find-file-containing-text/feed/ 0
find file by name in linux https://java2blog.com/linux-find-file-by-name/?utm_source=rss&utm_medium=rss&utm_campaign=linux-find-file-by-name https://java2blog.com/linux-find-file-by-name/#respond Sun, 23 Sep 2018 18:36:09 +0000 https://java2blog.com/?p=6506 In this post, we will see how to find file by name in linux.

You can use "find" command to find file by name.

Find file in the current directory

Here is a simple command to find file "letters.txt" in current directory.

find . -name letters.txt

$ find . -name letters.txt

./txtFiles/letters.txt

If you want to find a file by name that contains both upper case and lower case then run:

find . -iname letters.txt

$ find . -iname letters.txt

./LETTERS.txt
./txtFiles/letters.txt

Find file in the specific directory

1. Find file “letters.txt” in /home directory.

find /home -name letters.txt

2. Find file “letters.txt” in multiple directories /home and /opt.

find /home /opt -name letters.txt

3. Find file “letters.txt” in directory /home and remove it

find /home -type f -name letters.txt -exec rm -f {}

4. Find all files in /opt directory with txt extension

find /opt -name “*.txt”

5. Find all hidden files in /home directory and remove it

find /home -name “.*”

6. Find all empty files in directory /home

find /home -type f -empty

That’s all about how to find file by name in linux

]]>
https://java2blog.com/linux-find-file-by-name/feed/ 0