DmitrySemenov
DmitrySemenov

Reputation: 10315

zsh - evaluate variable inside `` (command substitution)

# remove all processes by port
# like killport 8000
killport() {
  kill `lsof -t -i:$1`
}

however when I'm trying to run the command I get this

killport 8000    
killport:kill:2: not enough arguments

Upvotes: 1

Views: 392

Answers (1)

mklement0
mklement0

Reputation: 437648

Try:

killport() {
  local port=$(lsof -t -i:"$1")
  [[ -n $port ]] && kill $port
}

Your problem was that if lsof -t -i:$1 didn't output anything - because nothing happened to be listening at the specified port - the kill builtin received no argument, causing it to complain.

With the solution above, if the specified port is not in use, there will be no output, but the exit code - as reflected in $? - will be 1.

Upvotes: 2

Related Questions