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.
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.
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
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"
#!
-line at the top. I chose the /bin/sh
shell (a POSIX shell) as there is nothing in your existing code that requires a specific other shell like bash
or zsh
(see also Which shell interpreter runs a script with no shebang?).=
character (see Spaces in variable assignments in shell scripts).printf
as a precaution as I don't know whether your data might eventually arrive from some external source, and echo
is known for sometimes having issues with some particular strings (see Why is printf better than echo?).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.