Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SHELL

bash xargs

# Basic syntax:
<command_1> | xargs <command_2>
# Where:
#	- the stdout of command_1 gets piped to xargs which executes command_2 on
#		every space, tab, or new-line-delimited input
# Note:
#	- this is similar to find..exec, but xargs is faster and more versatile
# 	- xargs allows tools like rm to accept standard input as arguments

# Example usage 1:
# Say you want to change the permissions of all directories and subdirectories
# of the current directory. You can run:
find . -type d | xargs chmod 777
# Note:
# 	- the -t flag causes xargs to print each command that will be executed
#		to the terminal, which is useful for debugging
#	- the -p flag will print the command to be executed and prompt the
# 		user to run it, which is also useful for debugging

# Example usage 2 (somewhat advanced):
find . -maxdepth 2 -type f -iname "*name*" | xargs -I {} sh -c "grep -l word1 $(grep -l word2 {})"
# Where:
#	- the find command identifies all files in the current directory and
#		subdirectories up to a depth of 1 that contain "name" in their
#		file name in a case-insensitive manner and pipes them to xargs
#	- -I specifies a string that will be replaced by the stdin when found (which
#		is useful for controlling where the piped content appears in the
#		xargs command)
#	- sh -c runs the shell command in quotes which can be used to do command
#		substitution in xargs
Source by shapeshed.com #
 
PREVIOUS NEXT
Tagged: #bash #xargs
ADD COMMENT
Topic
Name
2+7 =