0

I am assigning a variable to echo command which generates a random number.

For eg: n=$(echo $(( (RANDOM%6) +1)). I have to grep this variable in /etc/passwd.

So, my syntax reads like:

n=$(echo $(( (RANDOM%6) +1)) | grep "$n" /etc/passwd

But I get the entire file content(/etc/passwd) as output. I do not know where the syntax is wrong.

It is important I get the output in one line only.

  • Hint 1: Count your parentheses. Hint 2: The $(echo part is pointless; n=$(( (RANDOM%6) +1)) is sufficient. Hint 3: A pipe | creates child processes that run essentially in parallel. Do you think it makes sense to execute these two commands in parallel? – Uwe Mar 9 '15 at 19:54
  • 2
    Replace | by ;. – Cyrus Mar 9 '15 at 20:06
1

I notice your separating two commands that run in sequence and not sharing Io with a pipe rather than a semicolon. Try

n=$(echo $(( (RANDOM%6) +1)) ; grep "$n" /etc/passwd
  • 2
    The echo is still pointless. – roaima Mar 9 '15 at 21:58
  • grep -F "$((RANDOM%6+1))" /etc/passwd but (RANDOM%6)+1 == RANDOM%7 – Costas Mar 9 '15 at 22:05
0

For eg: n=$(echo $(( (RANDOM%6) +1)). I have to grep this variable in /etc/passwd.

So you're trying to print all lines of /etc/passwd that contain a random number from one to six?

Wouldn't that just be (assuming bash or zsh or ksh for $RANDOM, which the base POSIX shell does not support):

grep $((RANDOM%6+1)) /etc/passwd

If you need that random number elsewhere:

n=$((RANDOM%6+1))
grep $n /etc/passwd

I don't think this is what you're trying to do, but you've oversimplified your question and lost that intent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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