Home > Enterprise >  How to get the first element of a array?
How to get the first element of a array?

Time:07-04

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

CodePudding user response:

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

CodePudding user response:

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}
  • Related