Bash – assign array into variable as string

arraybashshellvariable

I have this code, it prints the correct result, but I can't figure out how to get the echo from the last line into a variable.

# hostname is 'tech-news-blog-324344' . Setting it into array host_name_array
IFS='-' read -r -a host_name_array <<< "$(hostname)" 
#removing the last part of string after last "-"
unset 'host_name_array[${#host_name_array[@]}-1]'
( IFS=$'-'; echo "${host_name_array[*]}" )  
#result is 'tech-news-blog'

How could get the value of the last line into a variable?
I've tried the following:

( IFS=$'-'; URL="${host_name_array[*]}" )

But I get the result "tech news blog" with spaces between pieces of array instead of '-'.

Best Answer

When IFS='-' read -r -a host_name_array <<< "$(hostname)" is ran, the array is (tech news blog 324344).

After the final element is removed with unset 'host_name_array[${#host_name_array[@]}-1]', the array is (tech news blog).

So, to get this to echo tech-news-blog, some substitution will have to be done, since echo "${host_name_array[*]}" will yield tech news blog:

With tr: echo "${host_name_array[*]}" | tr ' ' '-'

sed: echo "${host_name_array[*]}" | sed 's/ /-/g'

Related Question