各位大佬,問個shell問題。
我要批量關(guān)閉占用某個端口的進(jìn)程,執(zhí)行下面代碼
lsof -i:4237 | awk '{if (NR>1){print $2}}' | xargs kill -9
如果4237沒有相關(guān)進(jìn)程,
sof -i:4237 | awk '{if (NR>1){print $2}}' 就為空,導(dǎo)致管道后面的xargs kill -9操作缺少參數(shù)報錯
怎么判斷管道輸出是否為空?
需求:要實(shí)現(xiàn)如果isof -i:4237 | awk '{if (NR>1){print $2}}' 為空,管道后面的xargs kill -9就不執(zhí)行。
lsof -i:4237 | awk '{if (NR>1){print $2}}' | xargs -r kill -9
xargs --help就有的東西
用法:xargs [選項(xiàng)]... 命令 [初始參數(shù)]...
以所給<初始選項(xiàng)>和其它更多來自標(biāo)準(zhǔn)輸入的參數(shù)運(yùn)行指定<命令>。
長選項(xiàng)的必需和可選參數(shù)對相應(yīng)的短選項(xiàng)同樣為必需或可選。
-0, --null 各個項(xiàng)目由 null(空字符,不是空白字符)分隔;
同時停止對引用和反斜杠轉(zhuǎn)義的處理及對邏輯 EOF
的處理
-a, --arg-file=文件 從指定<文件>讀取參數(shù),不使用標(biāo)準(zhǔn)輸入
-d, --delimiter=分隔用字符 輸入流的各個項(xiàng)目使用指定<分隔用字符>進(jìn)行分隔,
不使用空白字符;同時停止對引用和反斜杠轉(zhuǎn)義的
處理及對邏輯 EOF 的處理
-E 終止符 設(shè)置邏輯 EOF(邏輯文件末尾)字符串;如果<終止符>
作為單獨(dú)一行輸入,所有剩余的輸入內(nèi)容將被忽略
(若同時使用了 -0 或 -d 選項(xiàng),則該選項(xiàng)失效)
-e, --eof[=終止符] 在指定<終止符>的情況下與 -E <終止符> 等效;
否則,視為文件末尾終止字符串不存在
-I R 和 --replace=R 相同
-i, --replace[=R] replace R in INITIAL-ARGS with names read
from standard input, split at newlines;
if R is unspecified, assume {}
-L, --max-lines=最大行數(shù) 每個命令行使用最多<最大行數(shù)>行的非空輸入行
-l[最大行數(shù)] 類似 -L,但在沒有給出<最大行數(shù)>信息時默認(rèn)為接受
最多一行非空輸入行
-n, --max-args=最大參數(shù)數(shù)量 設(shè)置每個命令行可使用的<最大參數(shù)數(shù)量>
-o, --open-tty Reopen stdin as /dev/tty in the child process
before executing the command; useful to run an
interactive application.
-P, --max-procs=MAX-PROCS 同時運(yùn)行至多<MAX-PROCS>個進(jìn)程
-p, --interactive 運(yùn)行命令前提示
--process-slot-var=VAR 在子進(jìn)程中設(shè)置環(huán)境變量<VAR>
-r, --no-run-if-empty 如果沒有指定任何參數(shù),則不運(yùn)行指定的<命令>;
如果未給出該選項(xiàng),指定的<命令>將至少運(yùn)行一次
-s, --max-chars=最大字符數(shù) 限制命令行長度的<最大字符數(shù)>
--show-limits 顯示命令行長度的限制
-t, --verbose 執(zhí)行命令前輸出命令內(nèi)容
-x, --exit 如果大?。ㄒ?-s)超出限制則退出
--help 顯示此幫助信息并退出
--version output version information and exit
Please see also the documentation at http://www.gnu.org/software/findutils/.
You can report (and track progress on fixing) bugs in the "xargs"
program via the GNU findutils bug-reporting page at
https://savannah.gnu.org/bugs/?group=findutils or, if
you have no web access, by sending email to bug-findutils@gnu.org.