0

I am on macOS.

Here is my source file:

#!/bin/bash

version=42

o_ver=$version
let "version+=1"
echo Compiling version $version up from $o_ver

# . . . many more lines

I want to extract the version number (42 in this case) and use it to set the r_ver variable in the following bash script:

#!/bin/bash

r_ver= ??

I tried using grep but most examples use the -P flag not available on macOS.

1 Answer 1

1

The following command extracts lines from sourcefile that start with version= (possibly indented):

<sourcefile grep '^[[:blank:]]*version='

To get the first line only, pipe to head -n 1 (important if there may be more matching lines):

<sourcefile grep '^[[:blank:]]*version=' | head -n 1

Your new script should assign the output of the above command to a variable. The variable will hold like version=42. Then you need to get rid of version=. Final snippet:

r_ver="$(<sourcefile grep '^[[:blank:]]*version=' | head -n 1)"
r_ver="${r_ver#*version=}"

AFAIK everything I used here is portable.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .