【问题标题】:Combines chmod and running script in one line not working in Bash将 chmod 和运行脚本组合在一行中,但在 Bash 中不起作用
【发布时间】:2016-07-14 15:14:27
【问题描述】:

具有以下 Bash 序列来创建文件、更改文件权限(可执行)并运行我想要在一行中执行最后 2 个命令的脚本:

$ touch dotfiles.sh
$ chmod +x ./dotfiles.sh
$ ./dotfiles

解决方案 1

我认为一个可能的解决方案是使用 && 运算符。所以./dotfiles 只有在chmod 成功时才会执行。

但是这个解决方案不起作用,bash 说文件不存在。有什么想法吗?。

(无效的解决方案)

注意:chmod 如果成功则返回 0。所以 && 完成了,但在第二部分失败 ./dotfiles.sh:

$ chmod +x ./dotfiles.sh && ./dotfiles.sh
-bash: ./dotfiles.sh: No such file or directory
$

更新:解决方案 1 是正确的。请参阅下面的完整解释。

【问题讨论】:

  • 一一执行命令是否有效?
  • @Roman 是的!当您先执行 chmod 然后执行 ./dotfiles 时,它会起作用。我们的想法是将它们放在一条线上。有什么想法吗?
  • touch dotfiles.sh && chmod +x ./dotfiles.sh && echo $? 的输出是什么?
  • 您已使dotfiles.sh 可执行,但您尝试运行dotfiles — 那是行不通的。将dotfiles.sh 复制到dotfiles 并使dotfiles 可执行,或者运行dotfiles.sh
  • 请注意,如果您无法运行./dotfiles.sh,那么您很可能在“shebang”行(#!/bin/sh 或类似)上遇到错误。如果命名的文件不存在,您可能会收到“找不到文件”错误 - 例如,如果您有 #!bin/sh,则缺少 /

标签: bash shell chmod


【解决方案1】:

更新:

建议的解决方案 1 实际上是有效的。在阅读了用户的 cmets 后,我发现问题可能出在 dotfiles.shcontent 上,而不是我要求的 bash 命令。

我遇到了什么问题?

在 dotfile.sh 文件中,我包含了 #!/usr/bin/env bash 而不是 #!/bin/bash。因此,当执行chmod +x ./dotfiles.sh && ./dotfiles.sh "No such file or directory" 问题时,指的是./dotfiles.sh 内容而不是“命令”本身(我认为)。

【讨论】:

    【解决方案2】:

    这应该可行。

    chmod +x dotfiles.sh; [ $? -eq 0 ] && ./dotfiles.sh
    

    【讨论】:

    • 它不会在./dotfiles 执行之前检查chmod 是否成功。
    • 根据@Kenavoz 添加了一个 chmod 成功测试
    • 对 OP 不起作用的 chmod +x ./dotfiles.sh && ./dotfiles.sh 有什么区别?
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2012-02-08
    • 2017-09-03
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2018-03-23
    相关资源
    最近更新 更多