0

The command I using is: ls -l . | totLines=$(wc -l) echo $totLines . My goal is display the total number of lines, but by assigning the output of wc -l a variable name, then displaying that variable's value. However this is not working. HOw can I create a variable out of the output from wc -l after it has obtained the lines it's processing from a previous ls command?

  • Don't parse ls except for your own eyes. In scripts you'd rather do count=(*); printf 'There are %d in total' "${#count[@]}" – Valentin Bajrami Dec 6 '16 at 17:48
2

Your pipe is not going to your inner shell in that case, so you would want to

totLines=$(ls -l . | wc -l)
printf '%s\n' "$totLines"

to do what you're trying here. The -l . part don't really make much of a difference in this case though, so you could leave them off. Also, beware that if any of your filenames contain a new line you'd get the wrong count this way.

  • Cool, another quick question. How can I then create another variable that contains computation the previous variable with some mathematical changes: totLines=$(ls -l . | wc -l) | final=$(($totLines-1)) | echo $final . It seems that the pipe only sends STDOUT by itself, but does not actually send the Variable with it's value. I am able to achieve this in a Script since the script saves the variable with it's value consistently. How cold I achieve this through one command with the CLI? – chromechris Dec 6 '16 at 18:09
  • Another piece of advice. Don't use ls -l for whatever you are trying to do. What is your final goal in this adventure? ls -l is just doomed to fail. – Valentin Bajrami Dec 6 '16 at 18:15
  • @user42076 right, the pipe sends stdout from the left process to the right process, that's what it does. If you want to run one command then the next you can just put ; between them. But as val0x00ff asked, what are you actually trying to do here? Parsing ls output is usually the wrong thing to do. . . – Eric Renouf Dec 6 '16 at 18:20
  • @val0x00ff & Eric,, my final goal was just playing and learning more about variables and one line commands :) I appreciate the help and advice guys :) – chromechris Dec 6 '16 at 18:36
  • 1
    @user42076 alright then. A pipe just connects stdout from the left to stdin on the right, and it runs them in subshells so you cannot alter variables in the parent environment, so mixing pipes and variable assignments is often the path to frustration – Eric Renouf Dec 6 '16 at 18:37

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.