简体   繁体   中英

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

I want to pass the output of a command as positional parameter to a script file. I am running the command below:

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

That command will give me a "name". What I want to do is pass that output again to a shell script file as positional parameter.

my-file.sh:

#!/bin/bash
#My First Script

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

So, basically what I want to do is something like this:

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

Just define a new function to check the whois output and use the return string in the if condition as below. This way you can avoid the multi-level pipeline while executing the script and rather just control it via a simple function.

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

But if you still want to pass via the command line, do

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

You can use command substitution to do that:

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

It is more straightforward to read than using a pipe and xargs , which is another working solution.

Use awk to select a proper column from the output. Then use xargs to pass its output as an argument to your script.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM