Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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
like image 604
Wai Yan Hein Avatar asked Jan 29 '23 07:01

Wai Yan Hein


2 Answers

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)"
like image 107
Inian Avatar answered Feb 05 '23 18:02

Inian


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.

like image 34
damienfrancois Avatar answered Feb 05 '23 17:02

damienfrancois