-1

I have a one-liner alias that I added to my .bash_profile to kill process running in 8080

alias kill8080="kill -9 $(lsof -n -i:8080 | grep LISTEN | awk '{print $2}')"'

when I execute kill8080, I get

-bash: kill: (36404) - No such process

but when I execute

lsof -n -i:8080 | grep LISTEN | awk '{print $2}' 89912

then kill -9 88912, terminates the process

what is wrong with the one-liner?

btw, This is on Mac OS X

3
  • OSX is off-topic here - however the issue is almost certainly that at least parts of your alias are being evaluated at creation time rather than at run time, due to improper quoting. Jul 16, 2018 at 17:49
  • any solution that works? Jul 16, 2018 at 17:59
  • This project works on Linux and Mac: github.com/jkfran/killport Mar 31, 2023 at 19:16

1 Answer 1

3

The alias cannot work properly as this statement is executed during alias creation and not during run time.

lsof -n -i:8080 | grep LISTEN | awk '{print $2}'

So your alias will only kill this process that opens the port 8080 at the time when you create the alias and not when you are using the alias. The process number created for the alias will be static unless you re-create your alias create a statement each time before running it. So you test this by doing:

alias test1="echo $(lsof -n -i:8080 | grep LISTEN | awk '{print $2}')"

The test1 alias will always echo the same process number even if you manually kill the process and restart another process for port 8080. So the only way to really do this is to a bash script to do this instead of using aliases.

Also, note that the step also will not work if subprocesses are returned for lsof in Ubuntu, but I suppose this is not the case in OSX, but just be aware of this. For multiple processes, you will need to use a loop to kill each one but ignoring any error as killing the main process could kill any subprocesses as well.

Edited: You can do this with a one-liner in bash, not as an alias. This will work even if multiple process numbers are returned.

for p in `sudo lsof -n -i:8080 | grep LISTEN | awk '{print $2}'`; do sudo kill -9 $p; done

PS: You can check all your aliases by entering alias at the command prompt. It's a quick way to verify what is actually being created.

2
  • well, in that case, if run source .bash_profile from terminal, shouldn't it kill the process running at 8080. It did not Jul 16, 2018 at 18:36
  • You aren't executing the kill part of the alias when you create the alias, but the process number is determined during creation. Those are two different things. You need to understand what $() does in alias statement. Jul 16, 2018 at 18:38

Not the answer you're looking for? Browse other questions tagged .