-1

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

Chrizz
  • 3
  • 3
  • It'd help to mention what format the array is in. It's a JS array, right? And it's JSON-compatible? BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Jul 03 '22 at 17:02
  • Please add output of `pm2 id ` to your question. – Cyrus Jul 03 '22 at 18:14

2 Answers2

2

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

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}
gabor.zed
  • 134
  • 1
  • 2
  • 6
  • This doesn't seem very helpful as clearly the output `[2]` is only a singleton, which doesn't seem the general case (otherwise the OP would have specified that)... – jthulhu Jul 03 '22 at 17:29