i have a list of apps that i need to forcequit and, from time to time, that list changes. perfect excuse to manage a single array! however, my strings with spaces aren't passing as i'd like them to. here's the simple script:
#!/bin/sh
#-----Array
apps=( firefox-bin firefox JavaApplicationStub groupwise "Google\ Chrome" "Microsoft\ Word" )
for i in "${apps[@]}"
do
killall $i
done
exit 0
when i generate verbose feedback, i'm seeing each app in question quit EXCEPT for those with spaces. on a mac, in the command line, i have to type the following to forcequit word and chrome:
killall Microsoft\ Word
killall Google\ Chrome
but i can't seem to find a way to paste the correct syntax into the array to get these applications to quit as the others do. in the above script example, the result just says:
"+ for i in '"${apps[@]}"'
+ killall 'Microsoft\' Word
No matching processes were found"
any thoughts on what i might be missing?
Use single quotes when creating the array:
apps=( firefox-bin firefox JavaApplicationStub groupwise 'Google Chrome' 'Microsoft Word' )
Using pkill may also be a better choice instead of killall .
This is the actual problem:
killall $i
killall "$i" # Prevent variable with spaces from splitting
Though really, I think your program could be rewritten as
killall "${apps[@]}"
People are understandably leery of 'killall', since on some other systems it has a far more, shall we say, literal meaning.
verdepollo: single quotes didn't work. tried that before i posted.
Corona688: many thanks, for the fix. didn't think to quote the variable.
cheers, folks,
d
With pgrep|pkill one does not need an array (and not a loop)
apps="firefox-bin|firefox|JavaApplicationStub|groupwise|Google Chrome|Microsoft Word"
pkill -x "$apps"
didn't know about pkill so thank you. otherwise, i'm all about elegance. if i can do something in two lines of code, i don't care what those two lines are. yours is great but as i'm already using arrays and not bothered by them, so is the earlier example.
As suggested, instead of a loop,
killall "${apps[@]}"