I can't get my bash script to assign variables within a loop:
#!/bin/bash
usercount=0
for word in userfile
do
let usercount=$usercount+1
done
echo $usercount
Output for usercount is always 0. Whats wrong with this?
You need while loop
to read the file line by line
:
usercount=0
while read l; do
let usercount=$usercount+1;
done < userfile
Though just to count line you can very well do:
usercount=$(wc -l < userfile)
If you want to count lines or words in a file, use wc
:
Words:
wc -w < file
Lines:
wc -l < file
Most people normally use double parentheses for shell arithmetic:
usercount=0
for word in userfile groupfile elephants
do
((usercount++))
done
echo $usercount
This snippet echoes 3
, corresponding to the three words. You can also use let
; most people don't. However, when I run your code, it echoes 1
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.