0

I'm trying to echo "It was not found" if the netstat returns no result. But, if it does return a result, then to display the netstat results.

I'm trying to google for what I'm using and can't find much about it.

#!/bin/bash

echo "Which process would you like to run netstat against?"
read psname
echo "Looking for '$psname'"
sleep 2
command=$(netstat -tulpn | grep -e $psname)
[[ ! -z $command ]]

It's to do with the [[ ! -z $command ]]

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ImKeelan
  • 25
  • 5
  • Which user runs this script? – Cyrus Oct 27 '20 at 20:32
  • Running as root at the moment – ImKeelan Oct 27 '20 at 20:34
  • What do you enter as `$psname`? – Cyrus Oct 27 '20 at 20:35
  • Any process which you'd like to view in netstat. For example, inputting chrome would return all netstat results relating to chrome. That works fine. I'm just trying to echo the message "It was not found" when the inputted process isn't running. For example inputting sjkdaskjlskj should return "It was not found" since there's no process running called that. – ImKeelan Oct 27 '20 at 20:36
  • I suggest: `[[ ! -z $command ]] || echo "It was not found"` – Cyrus Oct 27 '20 at 20:40
  • 1
    I tried that earlier and it didn't work but now it is haha, thank you anyway! – ImKeelan Oct 27 '20 at 20:43

2 Answers2

1

[[ ! -z $command ]] doesn't 'show' you any output.

Use a if/else setup to show the result;

if [[ ! -z $command ]]; then
    echo "$psname was found!"
else
    echo "No process named '${psname}' found!"
fi

Or a shorthand variant;

[[ ! -z $command ]] && echo "$psname was found!" || echo "No process named '${psname}' found!"

Note if the user input may contain a space, it's saver to use "" around the grep string;

command=$(netstat -tulpn | grep -e "$psname")

When to wrap quotes around a shell variable?

Jens
  • 69,818
  • 15
  • 125
  • 179
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

Do not intercept the output directly. You can instead do something like:

if ! netstat -tulpn | grep -e "$psname"; then
    echo "not found" >&2
fi

If grep matches any output, it will print it to stdout. If it mathches nothing, it returns non-zero and the shell will write a message to stderr.

William Pursell
  • 204,365
  • 48
  • 270
  • 300