gpt4 book ai didi

linux - Bash:使用字符串变量一个接一个地运行命令

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:10 25 4
gpt4 key购买 nike

我知道在 bash 中使用以下命令一个接一个地运行命令

command1 && command2

command1; command2

甚至

command1 & command2

我还了解到存储在 bash 变量中的命令可以通过简单地触发变量来运行:

TestCommand="ls"
$TestCommand

执行上述操作将列出目录中的所有文件,我已经测试过了。

但是对多个命令执行相同操作会产生错误。示例如下:

TestCommand="ls && ls -l"
$TestCommand
ls: cannot access &&: No such file or directory
ls: cannot access ls: No such file or directory

我的问题是为什么会发生这种情况,是否有任何解决方法?

在你抨击我做如此愚蠢的事情之前。前面只是提出问题。我的目录中有一个文件列表,我正在使用 sed 将该列表转换为单个可执行字符串。将该字符串存储在 bash 变量中,我尝试运行它但失败了。

最佳答案

当您将两个命令放在一个字符串变量中时,它将作为单个命令执行。所以当你使用 "$TestCommand" 执行两个 "ls" 命令时,它只执行一个(第一个)"ls" 命令.它将 &&ls(第二个)视为第一个 ls 命令的参数。

由于您当前的工作目录没有任何名为 && 和 ls 的文件,因此它返回错误:

    ls: cannot access &&: No such file or directory
ls: cannot access ls: No such file or directory

所以,基本上你的命令是这样的

    ls file1 file2 -l

如果 file1 和 file2 存在,它会给你这样的输出:

    HuntM@~/scripts$ ls file1 file2 -l
-rw-r--r-- 1 girishp staff 0 Dec 8 12:44 file1
-rw-r--r-- 1 girishp staff 0 Dec 8 12:44 file2

现在你的解决方案:

您可以创建函数或另外一个脚本来执行以下 2 个命令:

调用者.sh

    #!/bin/bash
myLs=`./myls.sh`
echo "$myLs"

myls.sh

    #!/bin/bash
ls && ls -l

关于linux - Bash:使用字符串变量一个接一个地运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com