【问题标题】:Bash script not working properly when run automatically自动运行时 Bash 脚本无法正常工作
【发布时间】:2012-12-15 01:47:10
【问题描述】:

我有一个 bash 脚本,它仅在我的笔记本电脑连接到网络时使用 notify-OSD 打印通知。所以我把 bash 脚本放在 /etc/network/if-up.d

我将一些日志消息打印到文件中以确认脚本确实在运行。但是通知的东西似乎不起作用。我刚刚将这一行添加到文件中

 notify-send -u 'critical' -i /home/vivek/Downloads/proxy.ico 'SetProxy Status' 'proxy set to auto'

但是,当我像这样从终端显式运行该脚本(通过双击它或)时:

cd /etc/network/if-up.d
./setproxy

setproxy 是 bash 文件的名称,然后我看到通知工作正常。为什么会有这种行为?我怎样才能解决这个问题?我正在使用 ubuntu 12.04

/tmp/trace 中的输出:

+ nmcli con status
+ grep -q 'Hostel\|IITD'
+ '[' 1 -eq 0 ']'
+ gsettings set org.gnome.system.proxy mode none

** (process:12320): WARNING **: Command line `dbus-launch     --autolaunch=673e71ca3fc5f402403d22380000000a --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n

** (process:12320): WARNING **: Command line `dbus-launch --autolaunch=673e71ca3fc5f402403d22380000000a --binary-syntax --close-stderr' exited with   non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
+ echo 'You are outside college! No Proxy'
+ notify-send -u critical -i /home/vivek/Downloads/proxy.ico 'SetProxy Status' 'You are outside college, proxy set to none'

【问题讨论】:

    标签: bash networking ubuntu notifications system


    【解决方案1】:

    我怀疑是环境问题。

    所以在你的脚本中,输入:

    #!/bin/bash -x
    
    source ~/.bashrc || source /etc/profile
    exec &>/tmp/trace
    # rest of the script there
    

    告诉我们发生了什么。

    编辑:您的脚本应以:

    开头
    #!/bin/bash
    
    source ~/.bashrc || source /etc/profile
    export DISPLAY=:0
    # rest of the script there
    

    【讨论】:

    • 感谢您的回复。为了清楚起见,你的意思是我需要添加这样的东西:#!源 ~/.bashrc || /etc/profile 而不是通常的 #!/bin/bash ?
    • @VivekPradhan,不,source 应该在#!/bin/bash之后的下一行
    • 好的@sputnick 我试过这个:#!bin/bash source ~/.bashrc || source /etc/profile ,但我仍然没有看到通知。您可以尝试放置一个仅显示通知的简单 bash 脚本并将其放入 /etc/network/if-up.d 中,然后告诉我您是如何工作的。
    • 查看我编辑的帖子以了解调试模式。然后使用 /tmp/trace 文件的输出编辑您的原始帖子
    • 非常感谢@sputnick!我已经用 /tmp/trace 的输出更新了我的问题
    【解决方案2】:

    如果您正在运行的程序需要 X,则它不能在没有 X 的情况下运行。或者以某种方式授权它连接到您的 X 会话,或者从您的 X 会话中运行它。

    【讨论】:

    • 非常感谢@triplee 的回复。我想你是对的,但我不明白为什么需要 Xauthorisation?我将尝试找出如何导出 Xsession 变量以进行授权。
    【解决方案3】:

    如果你想使用DISPLAY,你也必须设置XAUTHORITY,但这有点复杂(取决于用户名和随机字符串)试试这个:

    #!/bin/bash
    
    export displayOwner=vivek     # enter your usename here
    export DISPLAY=:0
    export XAUTHORITY=$(echo /var/run/gdm3/auth-for-${displayOwner}-*/database)
    
    notify-send -u 'critical' -i /home/vivek/Downloads/proxy.ico 'SetProxy Status' 'proxy set to auto'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-13
      • 2015-02-14
      • 2023-03-04
      • 2021-01-20
      • 1970-01-01
      • 2016-03-11
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多