1

I want to write shell script to output two variables in one line.

My script is:

SRC = "192.168.1.1"
PORT = "22"

I want to make the output looks like

192.168.1.1,22

How to do this? Thank you.

Kusalananda
  • 333,661

2 Answers2

3

To echo any number of variables just reference them in the same echo command. Also, note that the correct shell syntax for assignments must not have spaces around =.

#!/bin/sh
SRC="192.168.1.1"
PORT="22"
echo "$SRC,$PORT"

Result of running the script will be:

 $ ./test.sh
 192.168.1.1,22
kaylum
  • 531
  • 3
  • 6
2

You would typically use printf to output variables' data, like so:

#!/bin/sh

src=192.168.1.1
port=22

printf '%s,%s\n' "$src" "$port"

You may also find the following interesting, regarding quoting:


Alternatively,

#!/bin/sh

src=192.168.1.1
port=22

string="$src,$port"

printf '%s\n' "$string"

The only difference here is that I've created a new variable with the comma-delimited values of the two first variables, and then output that. This may be what you want depending on what your use of that string may be later in the script.

Kusalananda
  • 333,661