0

I wrote this script to store some information about my machine such as the users and the running processes .

I tried to store the retrieved data into an array. To test array I printed the length of an array as follows :

#!/bin/bash


###################################################################################

openFilesCount=$(lsof -Fn -u teeba| sort  | uniq | grep /home | wc -l);

openPortsCount=$(lsof -Fn -u teeba| sort  | uniq | grep /home | wc -l);

readingTime=$(date +%Y-%m-%d_%T);

usersArr=$(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd);

pidsArr=$(ps axo pid);

###################################################################################

echo "${#usersArr[@]}";

The output is 1 ... although the users are three ? do I need to split the retrieved data on "\n" for example before store it in the array ? if yes , how ?

2

You can use,

usersArr=($(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd) )

for i in "${usersArr[@]}"
do
    echo "$i"
done
| improve this answer | |
2

here try this

 #!/bin/bash
 array=(elem1 elem2)
 #to print the size of the array
 echo "${array[@]}"  
 #to access an individual member
 echo "element number ${#array[@]}"

Hope it helps

| improve this answer | |
  • see my update please! – Akari Feb 15 '14 at 13:38
  • There are few syntax errors in your code. Plz check before you post. – souravc Feb 15 '14 at 13:46
  • 1
    Sorry, no spaces in between the assingment operator and operands – Zuko Feb 15 '14 at 13:53
  • 1
    [1] do not use space when declaring a variable, [2] array elements should be separated by space not comma i.e., your array = ("elem1", "elem2", "elem3") should be var=(elem1 elem2 elem3) [3] array elements are ${array[@]} not just $array[@] – souravc Feb 15 '14 at 13:58
  • 1
    yeah, i noticed. and I'm gonna correct that. no commas but spaces. Thanks – Zuko Feb 15 '14 at 14:01

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.