user7898461
user7898461

Reputation:

Read first token from output

I have this command:

num_lines="$(wc -l "$HOME/my_bash_history")"

Which yields:

17 /Users/alex/my_bash_history

So I tried to get the first token using:

local read num_lines < <(wc -l "$HOME/my_bash_history")

But all I get is empty result:

num lines:

Anybody know why?

Upvotes: 1

Views: 157

Answers (2)

John1024
John1024

Reputation: 113914

wc reports the file name unless it is reading from stdin. So, keep it simple, just use:

$ num_lines="$(wc -l <"$HOME/my_bash_history")"
$ echo "$num_lines"
17

If you really want to use read with process substitution, then use two arguments to read like this:

$ read num_lines fname < <(wc -l "$HOME/my_bash_history")
$ echo "$num_lines"
17

or, use a here-string like this:

$ read num_lines fname <<<"$(wc -l "$HOME/my_bash_history")"
$ echo "$num_lines"
17

When read reads a line, the shell first splits the lines into words. The words are assigned to each argument in turn with the last argument receiving whatever remains. In our case, this means the the number is assigned to num_lines and whatever words follow the number are assigned to fname.

Upvotes: 3

UtLox
UtLox

Reputation: 4164

try this:

num_lines="$(wc -l $HOME/my_bash_history)"
echo "${num_lines%% *}"

explanation

${num_lines%% *}  # delete all after first blank

Upvotes: 2

Related Questions