Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
 
What, exactly, breaks? Also, you probably want to use $value in place of $1 in the grep command. –  chepner Jul 15 '13 at 13:46
 
Ok yes apologies that was meant to be $value after grep. –  ojhawkins Jul 15 '13 at 13:59
add comment

2 Answers

up vote 2 down vote accepted

You don't actually need wc:

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

You could improve the variable names

num_logins=$(last | grep -c "$username")
share|improve this answer
add comment

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

value="$1"
length="$(last | grep "$value" | wc -l)"
share|improve this answer
 
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). –  chepner Jul 15 '13 at 13:48
 
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 –  ojhawkins Jul 15 '13 at 14:02
 
You typed lenght by accident here. Are you mistyping at your terminal as well? –  chepner Jul 15 '13 at 14:03
 
@ojhawkins: what is the output of the command last? –  Benoit Jul 15 '13 at 15:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.