首页 > 解决方案 > Bash:在脚本内部运行时,`chmod a+x` 不起作用

问题描述

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

我只关心更新脚本的退出代码(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)

标签: bashchmodpermission-denied

解决方案


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

bash /test/update/update.sh

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


推荐阅读