Blue Sea
Blue Sea

Reputation: 351

Why doesn't the pipeline take effect in bash in Linux?

Here is to count the number of sessions by the same login user.

I could run the direct command if I know the specific user name, such as usera, as the following:

who | grep usera | wc -l

And if I don't know the current user, I need to user parameter. But the following codes don't work:

currentuser=`whoami`

sessionnumber=`who | grep "$currentuser" | wc -l`

What's the error?

Thanks!

Upvotes: 0

Views: 53

Answers (3)

Hugo G
Hugo G

Reputation: 16496

Looks like you are confused about parameters and variables.

What you are trying to get is likely

who | grep $(whoami) | wc -l

The $() is equivalent to the backticks you used.

When you write

sessionnumber=``

this will run whatever is within the backticks and save the output to a variable. You can then access the variable using the dollar notation:

echo "$sessionnumber"

Upvotes: 0

Jetchisel
Jetchisel

Reputation: 7791

Grep has the -c flag so the wc -l plus the additional pipe is not needed.

who | grep -c -- "$USER"

"$LOGNAME" is also an option instead of "$USER", which one is bash specific? I don't know, all I know is that they are both on Linux and FreeBSD system. The -- is just a habit just in case the user starts with a dash grep will not interpret it as an option.

Upvotes: 2

Vasil Velichkov
Vasil Velichkov

Reputation: 1324

sessionnumber=`who | grep "$currentuser" | wc -l`

You are assigning the result of the who | ... command to a variable and to see its value you can use echo $sessionnumber

Upvotes: 1

Related Questions