linux - Bash:在脚本中执行多命令行字符串

标签 linux bash unix

在一个文件中,有一些像这样的多命令行:

cd /home/user; ls

在 bash 脚本中,我想执行这些命令,向最后一个命令添加一些参数。例如:

cd /home/user; ls   -l *.png

我认为做这样的事情就足够了:

#!/bin/bash
commandLine="$(cat theFileWithCommandInside)   -l *.png"
$commandLine
exit 0

但是它说:

/home/user;: No such file or directory

换句话说,“;”字符不再表示“命令结束”:shell 正在尝试查找名为“user”的目录;在主文件夹中...

我试图替换“;”与“&&”,但结果是一样的。

最佳答案

你的问题的重点是执行存储在字符串中的命令。有数千种方法可以间接执行。但最终,bash 必须参与进来。

那么为什么不显式调用 bash 来完成这项工作呢?

bash -c "$commandLine"

来自文档:

-c string

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

http://linux.die.net/man/1/bash

关于linux - Bash:在脚本中执行多命令行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013319/

相关文章:

linux - 使用 Linux 命令行替换大文件中的字节

c++ - 进程被终止时智能指针的行为

linux - 锁定密码数据库

linux - 用于从 2 个不同文件中获取相同行的 bash 脚本

linux - Linux 中的所有者和用户

linux - 检查目录是否用 bash 挂载

linux - cp dir 递归排除 2 个子目录

bash - bash 3.0 的 sed 命令出现乱码

linux - 如何仅批量重命名部分文件名?

string - 从双引号 bash 脚本中包含的字符串中删除空格