0

I saw this line in bash script

kill -${2:-15} `cat $1.pid`

It's killing process but don't know what -${2:-15} means. Can anyone explain what it means?

samthegolden
  • 1,366
  • 1
  • 10
  • 26
user2761895
  • 1,431
  • 4
  • 22
  • 38
  • 3
    Not an easy read the first time, but http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 contains the answer ;-) All you need to do is search for `:-`, it will take you to the definition. If you're going to have to debug existing code, then you'll do well to understand what is contained there. Good luck. – shellter Jan 08 '18 at 16:34

2 Answers2

2

It means expand the positional parameter $2, or substitute with 15 if it is empty. So if the script is called with fewer than 2 arguments, the command will be:

kill -15 `cat $1.pid`
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

The <variable>:-<default> syntax means "use $<variable> if it's defined. Otherwise, use <default>":

https://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion

In this case, $2 is a positional parameter, or the second word you pass to the script. This code makes it optional -- if it's not used or empty it will default to the string 15.

The -15 flag sent to kill tells it the type of signal to send ... in this case TERM which should allow the process to quit gracefully.

For example, you could use:

script 123 9

This will send the KILL signal to cat 123.pid. I'm not sure what 123.pid is, but it probably has the process ID of a known process you want to kill.

If you just did script 123 it would send TERM instead.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Please don't link the ABS -- it's the W3Schools of bash, full of bad-practice examples and outdated information. Consider instead http://wiki.bash-hackers.org/syntax/pe, or https://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion, or https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html – Charles Duffy Jan 08 '18 at 16:43
  • (See http://wooledge.org/~greybot/meta/abs -- the record for the "abs" factoid for the freenode #bash channel; you'll note that the consensus has been that the ABS is a resource best avoided since that factoid's first revision in 2008). – Charles Duffy Jan 08 '18 at 16:46
  • @CharlesDuffy thanks, I didn't realize this – Explosion Pills Jan 08 '18 at 17:04