0

I have a problem with mktemp and grep.

OUT=$(mktemp /tmp/output.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1; }
awk -F: '{print $7}' /etc/passwd >> $OUT
grep -c $1 $OUT

In grep line, code not exits, not prints value of grep Please, help me to solve that problem.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
John
  • 9
  • What does `$1` contain when it is hanging. No matter what it contains, try quoting it as `"$1"` – Inian Jan 14 '20 at 12:13
  • $1 contains bash – John Jan 14 '20 at 12:25
  • 2
    I suspect that `$1` might be empty , which makes the last command `grep -c $OUT`. Calling `grep` with a single argument makes it wait for the second argument indefinitely. Can you debug and check what `$1` actually contains? – BlackPearl Jan 14 '20 at 12:30
  • s/wait for the second argument/wait for text on stdin/ (but otherwise, spot-on). – Charles Duffy Jan 15 '20 at 21:55
  • @John, please prove that (specifically, the expansion of `$1` having the value you expect) to us. Providing a transcript of your script running with `set -x` to enable debug logging would work, f/e. (That is to say, make the very first line the command `set -x`, and [edit] the output that generates into the question). – Charles Duffy Jan 15 '20 at 23:02

1 Answers1

0

BlackPearl above probably is correct - $1 likely is empty during your program execution. As a result, the grep command looks like this: grep -c $OUT which tells grep to look for $OUT in the stdin. stdin is the keyboard (I suspect) so grep will wait forever (well, until you press Ctrl-D or Ctrl-C).

To solve your problem, specify a parameter when you execute your script.

You can also avoid the problem entirely by counting all of the unique values in your passwd file like this:

OUT=$(mktemp /tmp/output.XXXXXXXXXX) || { echo "Failed to create temp file"; exit 1; }
awk -F: '{print $7}' /etc/passwd >> "$OUT"
sort "$OUT" | uniq -c  # count each unique value in passwd file column 7
Mark
  • 4,249
  • 1
  • 18
  • 27
  • If trying to show best-practice code, you should really be quoting expansions. If you don't control `IFS`, even the output from `mktemp` can be split in surprising ways when later used in an unquoted expansion (consider if `IFS=/`). – Charles Duffy Jan 14 '20 at 15:37
  • Modified code to quote expansions as suggested by @CharlesDuffy. – Mark Jan 15 '20 at 21:36