简体   繁体   中英

Echo multiple variables via single command in Bash

I would like to write the individual variables $my_<1 to 3>_web to the terminal, without having to manually write into script like echo $my_1_web , echo $my_2_web and echo $my_3_web .

Example of manual typing commands to terminal (or writing commands into script).

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"

Would that be possible, approach like this? If so, I would love for an answer.

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

I'm learning bash and I'm a new member of the GNU / Linux community. I apologize if a similar case happened somewhere...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM