Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

simplification of the variable in bash

instead of a long list of variables

my_1_web="some value1"
my_3_web="some value2"
my_2_web="some value3"
echo "web at $my_1_web
$my_2_web
$my_3_web"

is possible like this ?

my_1_web="some value1"
my_3_web="some value2"
my_2_web="some value3"
echo "web at $my_1-3_web"

1-3 like all variable from 1 to 3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’d probably be easier to use an array instead of numbered variables:

my_web=(
    "some value1"
    "some value2"
    "some value3"
    )

Then to print them like you want:

IFS=$'\n' echo "web at ${my_web[*]:0:3}"

This temporarily sets the "internal field separator" to a newline so that when we join the array elements (my_web[*]), it joins them on the newline. I’m also explicitly selecting elements 1-3, but you don’t actually need to do that in this case since those are the only elements that exist.

Note that Bash arrays are 0-indexed.

Due credit to Glenn Jackman‘s now-deleted answer for inspiring this echo command.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading