I’m trying to create a shell script getting the process id of the Skype app on my Mac.
ps -clx | grep ‘Skype’ | awk ‘{print $2}’ | head -1
The above is working fine, but there are two problems:
1)
The grep command would get all process if their name just contains “Skype”. How can I ensure that it only get the result, if the process name is exactly Skype?
2)
I would like to make a shell script from this, which can be used from the terminal but the process name should be an argument of this script:
#!/bin/sh
ps -clx | grep '$1' | awk '{print $2}' | head -1
This isn’t returning anything. I think this is because the $2 in the awk is treated as an argument too. How can I solve this?
Your
ps -cl1output looks like this:Thus, the last entry in each line is your command. That means you can use the full power of regular expressions to help you.
The
$in a regular expression means the end of the string, thus, you could use$to specify that not only does the output must haveSkypein it, it must end withSkype. This means if you have a command calledSkype Controller, you won’t pull it up:You can also simplify things by using the
ps -oformat to just pull up the columns you want:And, you can eliminate
headby simply usingawk‘s ability to select your line for you. Inawk,NRis your record number. Thus you could do this:Heck, now that I think of it, we could eliminate the
greptoo:This is using awk’s ability to use regular expressions. If the line contains the regular expression, ‘Skype$’, it will print the first column, then exit
The only problem is that if you had a command
Foo Skype, this will also pick it up. To eliminate that, you’ll have to do a bit more fancy footwork:The
while readis reading two variables. The trick is thatreaduses white space to divide the variables it reads in. However, since there are only two variables, the last one will contain the rest of the entire line. Thus if the command is Skype Controller, the entire command will be put into$commandeven though there’s a space in it.Now, we don’t have to use a regular expression. We can compare the command with an equality.
This is longer to type in, but you’re actually using fewer commands and less piping. Remember
awkis looping through each line. All you’re doing here is making it more explicit. In the end, this is actually much more efficient that what you originally had.