Open In App

Calling shell functions with xargs

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Unix and Linux operating systems, the “xargs” command is used to create and execute command lines from standard input. It reads from a given file or the standard input (stdin) and then runs a command for each data item. Xargs is primarily used to convert a list of items into command-line arguments. It is a versatile tool that can be used in various scenarios, including batch processing, file manipulation, and automation of repetitive tasks.

Common Uses: “xargs”

It can be used in cases where we need to process and transform a list of items into command-line arguments for another command. Some of the common uses of xargs are given below.

Method 1: Processing Files:

xargs can be used for processing files. We can use the “find” command in combination with xargs to locate files in the specified directory and perform different operations, like deleting them. For example, if we want to delete all files in a specified directory, type the command given below.

find <directory_path> -type f -name "*.bat" | xargs rm

Output:

Screenshot_2023-12-08_09_48_47

Deleting (.bat) Extension Files

The above command is using the “find” command in combination with “xargs” to locate all files with a “.bat” extension in the specified directory (<directory_path>) and then delete each of those files using the “rm” command.

Running Commands with Confirmation:

xargs also provide option that prompts confirmation before executing any command. For example we are prompting for confirmation before executing the rm command on files with a specific extension. Type the command given below.

find <directory_path> -type f -name "*.txt" | xargs -p rm

Output:

Screenshot_2023-12-08_10_19_00

Prompting Confirmation

The above command is using “find” to locate files with a “.txt” extension in a specified directory (<directory_path>). It then uses “xargs -p” to interactively prompt for confirmation before executing the “rm” command to remove each of those files. Then, for each file separately, we can answer with “y” (yes) to confirm deletion or “n” (no) to skip deletion.

Method 2: Find and Replace:

xargs can also be used for finding and replacing certain keywords from files. We can use the “sed” command in combination with xargs for locating files with a particular text and replace “oldtext” with “newtext”. For example, if we want to find and replace a certain keyword in all files in a specified directory, type the command given below.

grep -rl "<oldtext>" <directory_path> | xargs sed -i 's/<oldtext>/<newtext>/g'

Output:

Screenshot_2023-12-08_09_57_40

Finding and Replacing Keywords

The above command is using “grep” and “xargs” to search for files containing a specific text string and then using “sed” to replace that text with a new string. The “-r” option recursively searches through directories and “-l” outputs only the names of files containing the pattern.

Method 3: Deleting Files:

xargs can also be used for deleting files. We can use grep in combination with xargs to delete files with a specific extension. To delete all files with a specific extension in a specified directory type the command given below.

ls <directory_path> | grep ".<extension_name>" | xargs rm

Output:

Screenshot_2023-12-08_10_14_16

Deleting a Specific Extension File

After running the above command, ls command lists all items in <directory_path>. The “grep” command filters the list to include only those with “.conf” in their names. The “xargs rm” command then removes each item in the filtered list. As a result, all the files with (.conf) extension will be deleted.

Steps for calling shell functions with xargs:

There are multiple steps involved in using xargs to call shell functions. The required steps are given below

Step 1: Creating a Shell function

First open a text editor of your choice and then create a new script file with (.sh) extension. The first step is to define a shell function by creating a block of code that performs a specific task.

Output:

Screenshot_2023-12-22_11_24_35

Creating Script File in Mousepad

Now we created a shell function that calculates the factorial of a number in the script file. This code is encapsulated within a function, allowing us to reuse it throughout your script or command line. We can use any of the text editor available in Linux like “Mousepad”, “Leafpad”, “Vim” etc. The example code is given below.

# A shell function that calculates the factorial of a number
#!/bin/bash

factorial() {
local num=$1
local fact=1

# Check if the number is non-negative
if [ $num -lt 0 ]; then
echo "Error: Not for negative numbers."
return 1
fi

# Calculate the factorial using a loop
for ((i = 2; i <= num; i++)); do
fact=$((fact* i))
done

echo "Factorial of $num is: $fact"
}

# Calling the Function
factorial 10




In this example, the factorial() function takes a parameter (num) and calculates the factorial of that number using a loop. To make sure the input number is not negative, it includes some error checking.

Output:

Screenshot_2023-12-09_07_19_46

Simple Shell Function

To make sure that there is no error in the code run this script by typing “chmod +rwx script.sh” in the terminal. This command gives read, write and execute permission to the script, allowing it to be run as a program.

  • Then type “bash script.sh” to get the output.

Output:

Screenshot_2023-12-09_07_21_51

Executing Shell Function

Step 2: Using “xargs” to call shell function

Now we need multiple inputs for the shell function. We can use the “echo” command or another command to generate input arguments that will be processed by shell function when passed through xargs. To create a list of values or strings that the shell function will accept as input, we use “echo”. Type the code given below in the file where we have written shell function.

echo "1stParam 2ndParam 3rdParam" | xargs -n 1 -I {} bash -c shell_function {}



  • echo “1stParam 2ndParam 3rdParam”: The arguments you want to pass on to the shell function will be printed. This can be changed to any command that outputs the required arguments.
  • xargs -n 1: It specifies that xargs should pass only one argument at a time to the shell function.
  • -I {}: It replace the occurrences of {} in the command with the argument.
  • bash -c shell_functioin {}: It invokes a new Bash shell to execute the shell function with the provided argument.

Now just replace the shell_function{} with the actual name of our function and also replace the parameters with the ones we require after the echo command.

Output:

Screenshot_2023-12-22_11_27_44

Shell Function wtih xargs

Now just type “bash script.sh” in the terminal window to get the output.

Output:

Screenshot_2023-12-22_11_36_22

Executing the Script

Conclusion:

Using xargs to call shell functions allows for efficient processing of input data by transforming it into command-line arguments for a specified function. When substituting input items for placeholders, the -I {} option comes in handy and makes it easier to integrate shell functions with the xargs command. xargs allows for seamless integration with a wide range of input sources, enhancing the versatility and usefulness of command-line operations.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads