While the other answers are going to be more efficient (ie, they don't incur the overhead of spawning 4x subshells), some considerations re: OP's current sed
solution:
- in the 1st
sed
script the #
is used as the script delimiter
- in the 2nd
sed
script the /
is used as the script delimiter
- the error is being generated by the 2nd
sed
script because the /
also shows up in the data (ie, sed
can't distinguish between a /
used as a delimiter vs. a /
as part of the data)
- try using
#
as the script delimiter in the 2nd sed
command to eliminate the error message
As for the current regexes, this may be easier to address if we enable extended regex support (-E
or -r
), eg:
$ echo "$SSH_URL" | sed -nE 's#^.*:([^/]*)/.*$#\1#p'
myOrg
$ echo "$SSH_URL" | sed -nE 's#^.*/([^\.]*)\..*$#\1#p'
my-repogit
Eliminating the pipe/subshell with a here-string (<<< "$var"
):
$ sed -nE 's#^.*:([^/]*)/.*$#\1#p' <<< "$SSH_URL"
myOrg
$ sed -nE 's#^.*/([^\.]*)\..*$#\1#p' <<< "$SSH_URL"
my-repo
Pulling all of this into OP's current code:
$ REPO=$(sed -nE 's#^.*:([^/]*)/.*$#\1#p' <<< "$SSH_URL")
$ GIT_ORG=$(sed -nE 's#^.*/([^\.]*)\..*$#\1#p' <<< "$SSH_URL")
$ typeset -p REPO GIT_ORG
declare -- REPO="myOrg"
declare -- GIT_ORG="my-repo"
NOTES:
- the
$( ... )
construct will still require a subshell to be spawned (2 total in this case)
- consider getting into the habit of using lower-cased variable names (eg,
ssh_url
, repo
and git_org
) to minimize the (future) chance of overwriting system variables (eg, PWD, HOME, PATH)