Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into component parts in Linux Bash/Shell

Tags:

bash

shell

I'm writing the second version of my post-receive git hook.

I have a GL_REPO variable which conforms to:

/project.name/vhost-type/versioncodename

It may or may not have a trailing and/or preceding slash.

My current code misunderstood the function of the following code, and as a result it clearly duplicates $versioncodename into each variable:

# regex out project codename
PROJECT_NAME=${GL_REPO##*/}
echo "project codename is: $PROJECT_NAME"

# extract server target vhost-type -fix required
VHOST_TYPE=${GL_REPO##*/}
echo "server target is: $VHOST_TYPE"

# get server project - fix required
PROJECT_CODENAME=${GL_REPO##*/}
echo "server project is: $PROJECT_CODENAME"

What is the correct method for taking these elements one at a time from the back of the string, or guaranteeing that a three part string allocates these variables?

I guess it might be better to split into an array?

like image 697
Felkja Avatar asked Mar 05 '26 06:03

Felkja


2 Answers

#!/bin/bash

GL_REPO=/project.name/vhost-type/versioncodename
GL_REPO=${GL_REPO#/} # remove preceding slash, if any

IFS=/ read -a arr <<< "$GL_REPO"

PROJECT_NAME="${arr[0]}"
VHOST_TYPE="${arr[1]}"
PROJECT_CODENAME="${arr[2]}"

UPDATE: an alternative solution by anishsane:

IFS=/ read PROJECT_NAME VHOST_TYPE PROJECT_CODENAME <<< "$GL_REPO"
like image 123
Eugeniu Rosca Avatar answered Mar 06 '26 18:03

Eugeniu Rosca


You can use cut with a field separator to pull out items by order:

NAME=$(echo $GL_REPO | cut -d / -f 1)

You can repeat the same for other fields. The trailing/leading slash you can ignore (you'll get a NAME field being empty, for example) or you can strip off a leading slash with ${GL_REPO##/} (similarly, you can strip off a trailing slash with ${GL_REPO%%/}).

like image 37
AlBlue Avatar answered Mar 06 '26 19:03

AlBlue