Juan C.
Juan C.

Reputation: 113

name of current variable in bash pipe

In powershell $_ is the name of the current variable being passed with pipes. What is the equivalent of this in Bash?

Let's say I want to do this

echo "Hi" | echo "$_"
   prints Hi

Thanks

Upvotes: 5

Views: 3628

Answers (3)

Alfe
Alfe

Reputation: 59436

If you really need to access this value as a variable (for whatever reason) you can "fake" it using a subcommand in parenthesis as a variable name like this:

echo "Hi" | echo "$(cat)"

Upvotes: 0

kirelagin
kirelagin

Reputation: 13616

In Unix ideology there are no objects or variables. The main selling poing of Unix is that everything is plain text, so you just pass text from one command to another.

You can think that you just have one variable and you always use it implicitly. Your example is a bit weird, but the closest thing I can think of is cat command that takes whatever its input is (think about the only implicit variable) and outputs it, so

echo "Hi" | cat

prints

Hi

Upvotes: 0

fge
fge

Reputation: 121730

Bash (or any other Unix shell for that matter) has no such thing.

In PowerShell, what is passed through pipes is an object. In bash, this is the output (to stdout) of the command.

The closes thing you can do is use while:

thecmd | while read theline; do something_with "$theline"; done

Note that IFS (Input Field Separator) is used, you can therefore also do:

thecmd | while read first therest; do ...; done

Upvotes: 5

Related Questions