Home > Net >  simplification of the variable in bash
simplification of the variable in bash

Time:04-30

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

CodePudding user response:

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 the first three elements, 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.

  • Related