7

I have to split a URL string and assign variables to few of the splits. Here is the string

http://web.com/sub1/sub2/sub3/sub4/sub5/sub6

I want to assign variables like below from bash

var1=sub2
var2=sub4
var3=sub5

How to do this in bash?

1

3 Answers 3

11
x="http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
IFS="/" read -r foo foo foo foo var1 foo var2 var3 foo <<< "$x"
echo "$var1 $var2 $var3"

Output:

sub2 sub4 sub5

Or with an array:

x="http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
IFS="/" read -r -a var <<< "$x"
echo "${var[4]}"
declare -p var

Output:

sub2
declare -a var='([0]="http:" [1]="" [2]="web.com" [3]="sub1" [4]="sub2" [5]="sub3" [6]="sub4" [7]="sub5" [8]="sub6")'

From man bash:

IFS: The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command.

Sign up to request clarification or add additional context in comments.

1 Comment

For safety you should use: read -r: do not allow backslashes to escape any characters
3

This should work:

IFS=/ read -r proto host dummy var1 dummy var2 var3 dummy <<< "$url"

Or read -ra to read into an array. read -r makes backslash non-special.

This won't work in bash:

echo "$url" | read ...

because read would run in a subshell, so the variables wouldn't be set in the parent shell.

1 Comment

or use this: shopt -s lastpipe; set +m; echo "$url" | IFS="/" read -ra array
0

I think a better solution would be to assign the result of splitting into an array. For example:

IFS='/' read -a array <<< "http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"

Unfortunately, this will create 3 'extraneous' elements, which you will have to take care of!

echo ${array[*]}
http: web.com sub1 sub2 sub3 sub4 sub5 sub6

EDIT: In here ${array[1]} is an empty element!

1 Comment

Don't forget to quote properly: echo "${array[@]}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.