3

I am trying to run a command and store it in a variable.

length=`last | grep foouser | wc -l` 

It works fine but when I add a variable to the command it breaks.

value=$1
length=`last | grep $value | wc -l`

How can I get this second example to work by acceptomg a variable?

2
  • What, exactly, breaks? Also, you probably want to use $value in place of $1 in the grep command. Commented Jul 15, 2013 at 13:46
  • Ok yes apologies that was meant to be $value after grep. Commented Jul 15, 2013 at 13:59

2 Answers 2

4

You don't actually need wc:

length=$(last | grep -c "$value")

You could improve the variable names

num_logins=$(last | grep -c "$username")
Sign up to request clarification or add additional context in comments.

Comments

4

You should quote your variables properly. If they contain spaces your script might break:

value="$1"
length="$(last | grep "$value" | wc -l)"

4 Comments

Quoting $value as the argument to grep is important. Quoting the RHS of the two assignments is less so; word-splitting isn't performed, so I'm not sure there's any problem with leaving them unquoted (although it doesn't hurt to quote them, either).
still not luck, I am entering value="foouser" /n length="$(last | grep "$value" | wc -l)" then trying to echo $lenght and it returns nothing @Benoit @chepner
You typed lenght by accident here. Are you mistyping at your terminal as well?
I think you should use brackets properly "${value}".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.