0

Anyways I'm new to web development and I am trying to use and understand the command line more. I keep having to kill a process running on port 3000 because every time I try to restart it, it says "in use". So I kept having to write the same 2 lines on the command line to kill it and I decided I wanted to use a executable bash script instead so it would save time. I made the bash script but I don't know what's wrong with it.

#!/usr/bin/bash
x = sudo lsof -t -i:3000
sudo kill ${x} 
echo "Complete"

That's the script and the error is saying line 3 command not found. Thanks for your help!

  • 1
    Do the answers to ["How do I set a variable to the output of a command in Bash?"](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) cover your problem? – Gordon Davisson Apr 03 '21 at 03:07

2 Answers2

0
  • Do not put spaces around equal signs when used for assignment.
  • Opposite is true for double equals comparison (must have surrounding spaces).
  • Follow this syntax to store STDOUT from the lsof into a variable.
  • Always surround variable references in double quotes.
#!/usr/bin/bash
x="$( sudo lsof -t -i:3000 )"
sudo kill "${x}"
echo "Complete"

I did not try to run it. Should work much better now.

Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
  • It says x : failed to parse argument: '{x}' – mahamudaden Apr 03 '21 at 02:10
  • I'll help you debug it. After line 2, add a new line: echo "'$x'". Then run it again. You expect 1 and only one space-delimited token to be echoed. Anything else is an error and the lsof incantation will need tweaking. – Mike Slinn Apr 03 '21 at 02:27
0

You can accomplish this with less code by using bash command substitution.

#!/usr/bin/bash
kill $(sudo lsof -t -i:3000)
echo "Complete"
  • This is true. It is essentially a one-line version of the code in the OP. One line commands are harder to debug and more expensive to maintain. Quines are the worst, lol; https://en.wikipedia.org/wiki/Quine_(computing) – Mike Slinn Apr 03 '21 at 02:30
  • I definitely see your point, but in this case he only wants to execute one command and is already running into variable context issues and there's already a construct for this exact use case. – Michael Long Apr 03 '21 at 02:33
  • Perhaps it would be fair to say this is not actually less code because there are fewer letters. We have the same moving parts doing the same things, just all jammed together. You cannot weigh software. – Mike Slinn Apr 03 '21 at 02:36