Chrizz
Chrizz

Reputation: 13

How to get the first element of a pm2 array?

The command pm2 id <name> returns an array (e.g [2]), how would I get the first element from the array? I want to save the output in APP_ID=$(pm2 id <name>) so APP_ID ends up being 2

Upvotes: 0

Views: 3563

Answers (2)

gabor.zed
gabor.zed

Reputation: 312

If the output is "[2]", tahts a string, not an array. You just need to cut the first and last character off.

APP_ID=$(pm2 id <name>)
APP_ID=${APP_ID:1: -1}

Upvotes: 0

wjandrea
wjandrea

Reputation: 33145

I'm not familiar with pm2, but if the array is JSON-compatible (which it looks like it is), you can use jq, for example:

$ echo '[2]' | jq '.[0]'
2
$ echo '[3, 2]' | jq '.[0]'
3

Here's a related question with some other methods: get the first (or n'th) element in a jq json parsing

Upvotes: 4

Related Questions