【问题标题】:Bash: `chmod a+x` Not Working When Run Inside ScriptBash:在脚本内部运行时,`chmod a+x` 不起作用
【发布时间】:2020-09-09 10:38:11
【问题描述】:

我正在尝试通过脚本模拟更新过程。

我只关心更新脚本的退出代码(0 表示成功,任何其他值表示失败)。

我创建了一个名为 update.sh 的简单脚本来模拟更新:

#!/bin/bash

# 1=true, 0=false
success=1

if [ $success -eq 1 ] ; then
    # Success.
    exit 0
else
    # Failure.
    exit 1
fi

为了模拟下载的更新,我将update.sh 压缩到一个名为update-file.zip 的文件中。

我的主脚本提取update-file.zip 并运行update.sh

#!/bin/bash

# Create a fresh update folder.
rm -rfv /test/update && mkdir /test/update

# Simulate download by copying zip file to that folder.
cp -rf /update-file.zip /test/update/

cd /test/update
unzip -o update-file.zip

# Make the update script executable.
updateFile="/test/update/update.sh"
chmod a+x $updateFile

# Run the update.
/test/update/update.sh

if [ $? -ne 0 ] ; then
    echo "update failed"
else
    echo "update success"
fi

# Delete update folder.
rm -rfv /test/update

但是,当我运行我的主脚本时(即使使用sudo),我收到以下错误消息:

/test/update/update.sh: Permission denied

甚至没有使用服务(使用root 完成所有操作)有帮助,因为我仍然收到相同的错误消息。

似乎chmod a+x 在脚本中运行时不起作用,因为如果我在终端上运行chmod a+x /test/update/update.sh,一切正常。

每当chmod a+x 从脚本运行时,我在尝试运行受影响的脚本时都会收到“权限被拒绝”错误。

令我困惑的是,当我运行ls -l /test/update/update.sh 时,我得到以下信息:

-rwxrwxrwx 1 root root 131 Sep  9  2020 /test/update/update.sh

无论chmod a+x 是从终端还是脚本运行,输出都是相同的。

我在Ubuntu Server 20.04.1 LTS (Focal Fossa)

【问题讨论】:

  • 请在/test/update/update.sh 之前在您的脚本中尝试cat -v /test/update/update.sh 并确认它实际上是您的脚本内容?
  • 好的,给我几分钟。
  • 另外请检查您的文件是否没有 dos 行结尾。显式运行bash /test/update/update.sh 有效吗?
  • 也会检查您的第二条评论并返回结果。 :)
  • @KamilCuk 我对结果有点困惑。出于某种原因添加cat -v /test/update/update.sh 解决了这个问题。然后我删除了这个并尝试了bash /test/update/update.sh,这也解决了这个问题。我将选择使用bash 选项,因为它更有意义,但我想知道为什么尽管#!/bin/bash 已经存在于update.sh 中,但它仍然有效。另外,请将此添加为答案,以便我接受。 :)

标签: bash chmod permission-denied


【解决方案1】:

您可以显式运行文件的解释器:

bash /test/update/update.sh

此时不需要使文件可执行。

【讨论】:

    【解决方案2】:

    你能用吗

    /bin/bash /test/update/update.sh

    而不是

    /test/update/update.sh

    在脚本中。

    能否请您也提供一次以下命令的输出。

    ls -ld /test/update

    【讨论】:

    • 您好,感谢您的回答!这应该也可以,但是我之前已经接受了先前的答案。非常感谢分享! :)
    猜你喜欢
    • 2016-07-14
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多