- Linux Shell Scripting Cookbook(Third Edition)
- Clif Flynt Sarath Lakshman Shantanu Tushar
- 497字
- 2021-07-09 19:46:16
Passing formatted arguments to a command by reading stdin
Here is a small echo script to make it obvious as to how xargs provides command arguments:
#!/bin/bash #Filename: cecho.sh echo $*'#'
When arguments are passed to the cecho.sh shell, it will print the arguments terminated by the # character. Consider this example:
$ ./cecho.sh arg1 arg2 arg1 arg2 #
Here's a common problem:
- I have a list of elements in a file (one per line) to be provided to a command (say, cecho.sh). I need to apply the arguments in several styles. In the first method, I need one argument for each invocation, like this:
./cecho.sh arg1 ./cecho.sh arg2 ./cecho.sh arg3
- Next, I need to provide one or two arguments each for each execution of the command, like this:
./cecho.sh arg1 arg2 ./cecho.sh arg3
- Finally, I need to provide all arguments at once to the command:
./cecho.sh arg1 arg2 arg3
Run the cecho.sh script and note the output before going through the following section. The xargs command can format the arguments for each of these requirements. The list of arguments is in a file called args.txt:
$ cat args.txt arg1 arg2 arg3
For the first form, we execute the command multiple times with one argument per execution. The xargs -n option can limit the number of command line arguments to one:
$ cat args.txt | xargs -n 1 ./cecho.sh arg1 # arg2 # arg3 #
To limit the number of arguments to two or fewer, execute this:
$ cat args.txt | xargs -n 2 ./cecho.sh arg1 arg2 # arg3 #
Finally, to execute the command at once with all the arguments, do not use any -n argument:
$ cat args.txt | xargs ./cecho.sh arg1 arg2 arg3 #
In the preceding examples, the arguments added by xargs were placed at the end of the command. However, we may need to have a constant phrase at the end of the command and want xargs to substitute its argument in the middle, like this:
./cecho.sh -p arg1 -l
In the preceding command execution, arg1 is the only variable text. All others should remain constant. The arguments from args.txt should be applied like this:
./cecho.sh -p arg1 -l ./cecho.sh -p arg2 -l ./cecho.sh -p arg3 -l
The xargs-I option specifies a replacement string to be replaced with the arguments xargs parses from the input. When -I is used with xargs, it will execute as one command execution per argument. This example solves the problem:
$ cat args.txt | xargs -I {} ./cecho.sh -p {} -l -p arg1 -l # -p arg2 -l # -p arg3 -l #
The -I {} specifies the replacement string. For each of the arguments supplied for the command, the {} string will be replaced with arguments read through stdin.