将 chmod 和 运行 脚本组合在一行中,但在 Bash 中不起作用

Combines chmod and running script in one line not working in Bash

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

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

解决方案 1

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

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

(无效解决方案)

注意:chmod returns 0 如果成功。因此 && 已完成,但在 ./dotfiles.sh:

时第二部分失败
$ chmod +x ./dotfiles.sh && ./dotfiles.sh
-bash: ./dotfiles.sh: No such file or directory
$

Update: Solution 1 is correct. See my answer below to full explanation.

这应该有效。

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

更新:

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

我遇到了什么问题?

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