CertifcateJunky
CertifcateJunky

Reputation: 171

Obtaining the last elements of an array

I have a string that looks like this:

Current working dir is /usr/local/Cellar/clamav/0.99.4/share/clamav
Max retries == 5
ERROR: Can't create temporary directory /usr/local/Cellar/clamav/0.99.4/share/clamav/clamav-07bc3bfeabec6a3bd40e8c2fdf126323.tmp
Hint: The database directory must be writable for UID 501 or GID 20

Running data=$(echo $string | grep -o -E '[0-9]+') it provides a variable that looks like this: 0 99 4 5 0 99 4 07 3 6 3 40 8 2 126323 501 20. I'm assuming this is an array because when I run the following:

for el in "${data[@]}"
do 
  echo "${el}"
done

It will output:

...
99
4
07
...
501
20

What I need to do is get the last two numbers in this array (?) and put them into a command. How can I successfully extract the last two numbers from the given array?

Upvotes: 0

Views: 712

Answers (3)

CertifcateJunky
CertifcateJunky

Reputation: 171

As mentioned by Giles I do not have an array. I was however able to get the UID and GID into separate variables using the following:

data=$(echo $string | grep -o -E '[0-9]+')
usersUID=${data: -2}
echo $usersUID
#<= 20
usersGID=$(echo $data | tail -c 7 | cut -c1-3)
echo $usersGID
#<= 501

Upvotes: 0

Steven Black
Steven Black

Reputation: 2232

use

./my-script.sh | tail -2 | my-next-command

or write it to a temp file

Upvotes: 0

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

You don't have an array, you need more parentheses :

$ data=( $(echo $string | grep -o -E '[0-9]+') ) 
$ echo "${data[-1]}"
20

Upvotes: 2

Related Questions