最後更新: 2022-08-01
介紹
xargs reads items from the standard input,
delimited by blanks (which can be protected with double or single quotes or a backslash) or
newlines, and executes the command (default is /bin/echo)
目錄
常用參數
-r, --no-run-if-empty # 當 stdin 沒有 input 就不行 command
(Normally, the command is run once even if there is no input.)
-a file, --arg-file=file # Read arguments from FILE (instead of standard input)
-p, --interactive # Prompt the user about whether to run each command line
-d delim, --delimiter=delim # Multibyte characters are not supported
# a C-style character escape such as \n, or an octal or hexadecimal escape code
-0, --null # Input items are terminated by a null character instead of by whitespace
max-X
-L max-lines # Use at most max-lines nonblank input lines per command line (Implies -x)
-n max-args # Use at most max-args arguments per command line
-s max-chars # Use at most max-chars characters per command line
# including the command and initial-arguments and the terminating nulls at the ends
# The largest allowed value is system-dependent,
# and is calculated as the argument length limit for exec
-x, --exit # Exit if the size (see the -s option) is exceeded.
-s max-chars # Use at most max-chars characters per command line
# including the terminating nulls at the ends of the argument strings.
# The largest allowed value is system-dependent
# (The argument length limit for exec)
# If this value is more than 128KiB, 128KiB is used as the default value;
Checking: The argument length limit for exec
getconf ARG_MAX
2097152 # 相當於 2KiB
-E eof-str # Set the end of file string to eof-str.
-I replace-str # 以 placeholder 取化 args
Example
files.txt 的內容
1 a 2 b 3 c 4 d
Example 1: Basic Usage
cat files.txt | xargs echo
cat files.txt | xargs # 結果與上一句相同, 預設 CMD 係 echo
# 預設是一行過全輸出, 亦即是
1 a 2 b 3 c 4 d
more
"ls -1 /etc/ssh/*key.pub | xargs" 與 "ls /etc/ssh/*key.pub | xargs" 相同 result
Example 2: read args from file
xargs -a files.txt echo
xargs -a files.txt
Example 3: # 問是否執行
xargs -p -a files.txt rm
rm 1 a 2 b 3 c 4 d ?...
Example 4: 每 N 一組組執行
# 每 1 行 一組, 相當於 `cat`
xargs -a files.txt -L 1 echo
# 每 2 行 一組
xargs -a files.txt -L 2
1 a 2 b
3 c 4 d
# 每 3 個 一組
xargs -a files.txt -n 3
1 a 2
b 3 c
4 d
Notes
ls -1 /etc/ssh/*key.pub | xargs -L 1 ssh-keygen -l -f
ls /etc/ssh/*key.pub | xargs -n 1 ssh-keygen -l -f
Example 5: 安裝一堆 PHP Package
yum list | grep php56u | grep -v -e debuginfo -e devel | cut -f 1 -d' ' > php-package.txt
xargs -a php-package.txt yum install
進階應該
-I replace-str
# Replace occurrences of replace-str in the initial-arguments with names read from stdin
# replace-str 可以理解為一個 placeholder
# Implies -x and -L 1
應用 1: Delete File
# 為了安全, 必須加上 tmp/
xargs -a list.txt -I{} mv {} tmp/
應用 2: 轉 Folder 名
xargs -a FolderName.txt -I{} doveadm mailbox mutf7 -7 "{}"