0

sometimes I need to follow a process and I always find a bash-script doing pid=$1. As far as I understand, it should get the process ID that I sent to the first shell instance I created that is running that particular process, and I could use it later (for instance, to kill it, or follow memory usage, or whatever). pid=$0 should get the current instance (bash) and pid=$! the latest one. (Please, correct if I'm wrong)

Problem is: every time I need to run pid=$1 command, pid gets nothing and echo $pid or echo ${pid} prints and empty line, I always need to fancy a way of doing it using pid=$! instead, since it's the only thing that gets my process ID. Does anyone know why my terminals behavior like that? (it's happening either in Linux Mint or in Fedora)

rafa
  • 795
  • 1
  • 8
  • 25
  • `$0` and `$1` get the positional parameters fed to the script (or function). In order for those to be PIDs, the script/function would need to have been passed the PIDs as arguments. Oh, and `$0` will likely never be a PID, because it's generally the name of the script/function - the actuall arguments start with `$1`... – twalberg Jul 16 '13 at 15:40
  • @twalberg Does it only work in a script file? I mean, if I try to run it directly on terminal, is that not supposed to work? – rafa Jul 16 '13 at 15:54
  • Typically, the shell running in your terminal will have been called with no arguments, so `$1` will be empty, and `$0` will just contain the name of your shell. You may have used `set` to change that at some point, though, so check things out with e.g. `echo "$1"`, etc... – twalberg Jul 16 '13 at 16:21
  • 1
    rafa, you've misunderstood, or picked very bad code as an example. !sorry!.. as others have said, `$$` current shells pid, `$!` most recent process put in back ground, etc. Do `set -- "my First Position" "2" 3; echo $1; echo $2; echo $3;` for a non-typical example of positional parameters. Good luck. – shellter Jul 17 '13 at 02:03
  • @shellter so this `$!` is really the most common way to do it? Oh, now I see, `$1`, `$2`, ... only worked in those cases because they have been `set` somewhere else. Everything is clearer now, thank you – rafa Jul 17 '13 at 11:50
  • 1
    As I said, `set ....` is a non-typical use of positional params. You're more likely to see them inside a script like `#....script code ... if [[ -d $1 ]] ; then ls -l $1 ; echo first arg on cmdline was a Dir; echo the dirname submitted was $1; fi #.... more script, possibly other refs to other pos params... if [[ -f $2 ]] ; then ls -l $2; echo 2nd arg was file; echo filename submitted was $2; fi` . Good luck. – shellter Jul 17 '13 at 13:41

1 Answers1

4

$$ should give you the script pid

$PPID should give you the caller (parent) pid


Answer of comment

sleep 100 &
sleeppid=$!
echo "PID=$sleeppid"
Eun
  • 4,146
  • 5
  • 30
  • 51