簡體   English   中英

將命令的輸出作為位置參數傳遞給 Linux shell 腳本中的腳本文件

[英]Passing output of a command as positional parameter to script file in Linux shell scripts

我想將命令的輸出作為位置參數傳遞給腳本文件。 我正在運行以下命令:

whois -h 192.168.0.13 google.com | grep -e Domain\ Name

該命令會給我一個“名字”。 我想要做的是將該輸出作為位置參數再次傳遞給 shell 腳本文件。

我的文件.sh:

#!/bin/bash
#My First Script

if [ $1 == "my-domain-name" ]; then
   echo "It is ok"
   exit 1
fi

所以,基本上我想做的是這樣的:

whois -h 192.168.0.13 google.com | grep -e Domain\ Name | -here pass the Name to my-file.sh and run that file

只需定義一個新函數來檢查whois輸出並在 if 條件中使用返回字符串,如下所示。 通過這種方式,您可以在執行腳本時避免多級管道,而只需通過一個簡單的函數來控制它。

get_whois_domainName() {
    whois -h 192.168.0.13 google.com | grep -e Domain\ Name
}

if [ "$(get_whois_domainName)" = "my-domain-name" ]; then
   echo "It is ok"
   exit 0
fi

但是如果您仍然想通過命令行傳遞,請執行

my-file.sh "$(whois -h 192.168.0.13 google.com | grep -e Domain\ Name)"

您可以使用命令替換來做到這一點:

my-file.sh "$(whois -h 192.168.0.13 google.com | grep -e Domain\ Name)"

與使用管道和xargs ,它更易於閱讀,這是另一種可行的解決方案。

使用awk從輸出中選擇合適的列。 然后使用xargs將其輸出作為參數傳遞給您的腳本。

whois google.com | grep -e Domain\ Name | awk '{ print $3 }' | xargs bash ./test.sh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM