【问题标题】:Will this script produce an error?这个脚本会产生错误吗?
【发布时间】:2013-12-20 02:18:34
【问题描述】:

我即将进行一项测试,这是学习指南中的问题之一,但我不确定哪个是正确答案。我相信答案是第四个选择。有人可以确认吗?

考虑以下 Bash 脚本。以下哪个说法是正确的?

#!/bin/bash
echo "ls" > newscript.sh
for i in {1..6}
do
    let REM=($i % 2)
    chmod -x newscript.sh
    if [ $REM -eq 0 ]
    then             
chmod +x newscript.sh
    fi
done
./newscript.sh

选择一个:

newscript.sh 不会运行,因为没有设置执行位

newscript.sh 将运行但不产生输出

newscript.sh 将运行,因为设置了执行位

newscript.sh 将运行但会产生错误

newscript.sh 不会运行,因为它不是一个有效的脚本

【问题讨论】:

  • 您可以从 Live CD 运行 Linux 并尝试一下。

标签: bash shell echo chmod


【解决方案1】:

newscript.sh 将运行,因为设置了执行位。

我怎么知道?因为我试过了。

让我们看看迭代(1 - 6 INCLUSIVE)

i = 1. 1 % 2 = 1: Will not be executable
i = 2. 2 % 2 = 0: Will be executable
i = 3. 3 % 2 = 1: Will not be executable
i = 4. 4 % 2 = 0: Will be executable
i = 5. 5 % 2 = 1: Will not be executable
i = 6. 6 % 2 = 0: Will be executable

百分号是取模运算符(即。A % B:认为它是 A 除以 B 的余数)

所以最后,脚本将是可执行的。如果您可以访问 Linux 机器,请自行尝试并添加一些调试语句来跟踪它。

【讨论】:

    【解决方案2】:

    例如,将文件保存到 a.sh,然后使用此命令运行它

    bash -x a.sh
    

    您应该会看到如下输出:

    $ bash -x a.sh
    + echo ls
    + for i in '{1..6}'
    + let 'REM=(1 % 2)'
    + chmod -x newscript.sh
    + '[' 1 -eq 0 ']'
    + for i in '{1..6}'
    + let 'REM=(2 % 2)'
    + chmod -x newscript.sh
    + '[' 0 -eq 0 ']'
    + chmod +x newscript.sh
    + for i in '{1..6}'
    + let 'REM=(3 % 2)'
    + chmod -x newscript.sh
    + '[' 1 -eq 0 ']'
    + for i in '{1..6}'
    + let 'REM=(4 % 2)'
    + chmod -x newscript.sh
    + '[' 0 -eq 0 ']'
    + chmod +x newscript.sh
    + for i in '{1..6}'
    + let 'REM=(5 % 2)'
    + chmod -x newscript.sh
    + '[' 1 -eq 0 ']'
    + for i in '{1..6}'
    + let 'REM=(6 % 2)'
    + chmod -x newscript.sh
    + '[' 0 -eq 0 ']'
    + chmod +x newscript.sh
    + ./newscript.sh
    

    它清楚地表明最后一个chmod是+x,所以脚本将运行,因为执行位被设置。

    【讨论】:

      猜你喜欢
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2021-12-31
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多