You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过pkexec单提示执行需认证的两条命令?

Run Multiple Privileged Commands with One pkexec Prompt

Hey there! As a fellow Linux user who's definitely groaned at repeated auth prompts, I've got you covered. Here are two straightforward ways to run two (or more) privileged commands with just one pkexec authentication pop-up:

Method 1: Use bash -c to Chain Commands Directly

You can pass both commands to bash via pkexec, using either && (run the second command only if the first succeeds) or ; (run the second command regardless of the first's outcome).

Example with && (success-dependent):

pkexec bash -c "apt update && apt install -y htop"

This will first update your package lists, and only install htop if the update completes without errors.

Example with ; (always run both):

pkexec bash -c "systemctl restart nginx; tail -n 20 /var/log/nginx/error.log"

Here, it'll restart Nginx and then show the last 20 lines of the error log, even if the restart hits a snag.

Note on Quotes:

If your commands include double quotes, wrap the entire command string in single quotes to avoid syntax issues:

pkexec bash -c 'echo "Admin message logged" >> /var/admins/log.txt && chmod 600 /var/admins/log.txt'

Method 2: Use a Script (Better for Complex Commands)

If you're dealing with longer or more complex commands, putting them in a script makes things cleaner and easier to edit later.

  1. Create a script file (e.g., privileged_tasks.sh):
    nano privileged_tasks.sh
    
  2. Add your commands to the script:
    #!/bin/bash
    # First privileged command
    apt update
    # Second privileged command
    apt upgrade -y
    
  3. Make the script executable:
    chmod +x privileged_tasks.sh
    
  4. Run it with pkexec (only one auth prompt needed):
    pkexec ./privileged_tasks.sh
    

Both methods work because pkexec runs the entire bash session or script as root, so every command inside inherits that elevated privilege—no need to re-authenticate for each one!

内容的提问来源于stack exchange,提问作者Hamlet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:35:33