0
pid=$(pgrep 'engrampa') #Get the PID of the engrampa processes .
killpid=$(echo $pid | head -1) #Get only the first line of the $pid variable and put into a new variable called $killpid.
kill $killpid

I want to maintain only the first line of the variable $pid.

Let's say I have 3 instances of the engrampa process open.

When I run the commands above step by step at terminal, I get exactly what I want: 2590

https://i.stack.imgur.com/L3U2g.jpg

When I run those exaclty commands in a script I get this result: 2590 18425 18449

https://i.stack.imgur.com/RuGX9.jpg

Why is that happening?

  • 1
    Which shell are you using in the terminal? perhaps it is not word-splitting the unquoted `$pid`, whereas the non-interactive `bash` shell is (see for example [Why are embedded newlines in command expansion replaced with whitespaces?](https://unix.stackexchange.com/questions/267931/why-are-embedded-newlines-in-command-expansion-replaced-with-whitespaces)) – steeldriver Dec 17 '18 at 23:43
  • There is an excellent article on how to do [process management](https://mywiki.wooledge.org/ProcessManagement) at Greg's Wiki. – l0b0 Dec 18 '18 at 00:12

1 Answers1

1

Edit: Identified my problem thanks to steeldriver comment.

Running echo $pid | head -1 in bash do nothing. Running the same command at zsh shell I get exactly what I want.

bash shell output -> 2590 18425 18449

zsh shell output -> 2590

That being stated, my problem has been solved changing the shell of the script to #!/bin/zsh.

Edit: Another solution, and more suitable, is just using echo $pid | awk '{print $1}' instead echo $pid | head -1. It works on both shell. Thanks to Christopher comment.

  • Your original version would have worked in `bash` if you'd quoted the variable: `echo "$pid" | head -1`. However you might want to consider using `pgrep -n` or `pgrep -o` (or `pidof` with the `-s` switch) so as to avoid piping to `head` altogether. – steeldriver Dec 18 '18 at 01:16