由其他使用者執行時命令行為不同(透過 su -c)

由其他使用者執行時命令行為不同(透過 su -c)

我想殺死與特定鏈匹配的每個進程。這是我的腳本,效果很好:

echo `ps aux | grep verySpecificChain | grep -v grep | /usr/bin/awk '{ print $2 }'` | xargs kill

現在我想透過“su -c”從其他用戶執行此腳本:

echo password | su -c "echo `ps aux | grep verySpecificChain | grep -v grep | /usr/bin/awk '{ print $2 }'` | xargs kill" userName;

我的問題是,當grep verySpecificChain匹配多個進程時,只有第一個元素被傳遞給xargs kill

30598  ==> killed
bash: line 1: 30599: command not found  ==> Not killed
bash: line 2: 30600: command not found  ==> Not killed
bash: line 3: 30606: command not found  ==> Not killed

我真的很想了解為什麼有或沒有su -c命令行為改變?

我在 Fedora 20 上運行 GNU bash,版本 4.2.53(1)-release (x86_64-redhat-linux-gnu)。

答案1

只是pkill -f verySpecificChain

答案2

我無法解釋你的例子中到底失敗了什麼(所以我承認這是我這邊的某種巫毒編程),但這是一個在我的 bash (Debian) 中有效的修復(幾乎 - 見下文*):

  • 擺脫裡面的echo
  • 逃脫$2

結果:

echo password | su -c "ps aux | grep verySpecificChain | grep -v grep | /usr/bin/awk '{ print \$2 }' | xargs kill" userName;

*我寫了“幾乎可以工作”,因為 Debian 不允許我su在管道中使用來回顯密碼。我必須在沒有首字母的情況下運行它echo並以互動方式輸入密碼。我想這在 OP 的 Fedora 中不是問題。

相關內容