0

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?

1
  • It seems that you're appending the number to end of the user output. Try this: y[$i]=$(who | cut -d " " -f1 | sort | uniq | sed "s/$/${ip}". Commented Nov 27, 2019 at 4:11

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I'd also recommend double-quoting references to $username, just in case of weird characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.