-2

I would like to store the output of a function (in that case the number of character given by wc) into a variable. I can output the number of char as follows and it works

FILE=textfile.txt
wc -c < $FILE

However, I could not store the number of char into a variable as in the following example.

FILE=textfile.txt
nchar=${wc -c} < $FILE
echo nchar

How could I do it?

ecjb
  • 5,169
  • 12
  • 43
  • 79
  • 6
    Try `nchar=$(wc -c < $FILE)`. – pmf Aug 15 '23 at 12:35
  • 2
    also, `echo nchar` says to echo/print the literal string `nchar`; to echo/print the contents of the variable you want `echo "${nchar}"`; in this case the braces are optional, ie, `echo "$nchar"` also works; while `echo $nchar` (no double quotes) also works, it's good practice to wrap variable references in double quotes to maintain original spacing and forego (usually unwanted) [word splitting](https://mywiki.wooledge.org/WordSplitting) – markp-fuso Aug 15 '23 at 12:50
  • many thanks for your helpful comments! – ecjb Aug 15 '23 at 13:04
  • 1
    [Shellcheck](https://www.shellcheck.net/) identifies several problems with the code. The report includes links to more information about the problems and how to fix them. It's a good idea to run [Shellcheck](https://www.shellcheck.net/) on all new and modified shell code. – pjh Aug 15 '23 at 13:22

0 Answers0