Alex
Alex

Reputation: 43

Problem with putting value in array in bash

I would like to make array which put users in a time using for loop. For example:

y[1]="user1"

y[2]="user2"

...

y[n]="usern"

I tried to do it like this

#!/bin/bash

x=$(who | cut -d " " -f1 | sort | uniq | wc -l)

for (( i=1; i<=$x; i++ )); do
        y[$i]=$(who | cut -d " " -f1 | sort | uniq | sed -n '$ip')
        p[$i]=$(lsof -u ${y[$i]} | wc -l)

        echo "Users:"
        echo ${y[$i]}
        echo -e "Number of launched files:\n" ${p[$i]}
done

Most likely I'm using command "sed" wrong. Can you help me?

Upvotes: 0

Views: 50

Answers (1)

Bayou
Bayou

Reputation: 3461

Indeed your sed command seems to be a bit off. I can't really guess what you're trying to do there. Besides that, I'm wondering why you're executing who twice. You can make use of the data first obtained in the following manner.

#!/bin/bash

# define two arrays
y=()
p=()
#x=0

while read -r username; do
        y+=("$username")
        p+=($(lsof -u $(id -u "$username") | wc -l))

        echo -e "User:\n${y[-1]}"
        echo -e "Open files:\n${p[-1]}"

        # The -1 index is the last index in the array, but you
        # could uncomment the x=0 variable and the line below:
        #((x++))

done <<< $(who | cut -d " " -f1 | sort | uniq)

echo "Amount of users: $x"
exit 0

Upvotes: 2

Related Questions