Manuel
Manuel

Reputation: 27

How can I store command output in a variable not on just one line?

The command output gets stored in a variable. Currently my script outputs it all on one line, instead of keeping it seperated on multiple lines. Which is not what I want, because this way it looks unorganized and is hard to read. How can I store the command output in my variable, so that it will get printed out on multiple lines and not just one?

#! /bin/bash

#User input
echo -n 'Enter IP: '
read IP

#Scanning the Ports
ports=$( nmap -sS $IP | grep open)

#Output
echo $ports

Example:

What it currently outputs

21/tcp open ftp 22/tcp open ssh 23/tcp open telnet

What I would want it to output

21/tcp open ftp 
22/tcp open ssh 
23/tcp open telnet

Upvotes: 1

Views: 1039

Answers (1)

William Pursell
William Pursell

Reputation: 212248

You need to use quotes.

echo "$ports"

When bash sees the line without quotes, it performs word splitting. In other words, it's as if you executed:

echo 21/tcp open ftp\
22/tcp open ssh\
23/tcp open telnet

Which treats the newlines no differently that the spaces, and passes each argument to echo. It then writes each argument, separated by a single space.

Upvotes: 4

Related Questions