Bash shell 脚本,如何在命令中使用管道
Bash shell scripting , how to use pipes in command
正在尝试在 bash 脚本中使用管道。这在我的 Linux shell 上运行良好,但 bash 脚本出错。我做错了什么?
#!/bin/bash
#some code
cmd="cat file2 | grep ':' | awk -F \":\" '{print $1}' > pool_names"
echo $cmd
exec $cmd
我看到这个错误
cat: invalid option -- 'F'
Try 'cat --help' for more information.
bash 内置 exec
命令具有完全不同的目标,如 https://www.computerhope.com/unix/bash/exec.htm 所述。
您必须将 exec
替换为 eval
才能使您的脚本正常工作,或者如@Jonathan Leffler 在评论中所建议的那样,您可以使用 bash -c "$cmd"
.
在 shell 中,“简单命令”是一系列可选的变量赋值和重定向,顺序任意,可选地后跟单词和重定向,由控制运算符终止。 (参见 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01), while a pipeline is a sequence of one or more commands separated by the control operator '|' (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02)。当 shell 看到行 exec $cmd
时,它没有看到控制运算符 |
,所以这是一个简单的命令。 (这与 exec
无关,任何命令都会发生相同的行为。)然后扩展行中的变量并遵循规则 the first field shall be considered the command name and remaining fields are the arguments for the command
,因此调用 exec
有一堆论据。 exec
不会尝试将参数解释为 shell 运算符(也许您打算使用 eval
而不是 exec
),而只是将所有参数传递给 cat
.
正在尝试在 bash 脚本中使用管道。这在我的 Linux shell 上运行良好,但 bash 脚本出错。我做错了什么?
#!/bin/bash
#some code
cmd="cat file2 | grep ':' | awk -F \":\" '{print $1}' > pool_names"
echo $cmd
exec $cmd
我看到这个错误
cat: invalid option -- 'F'
Try 'cat --help' for more information.
bash 内置 exec
命令具有完全不同的目标,如 https://www.computerhope.com/unix/bash/exec.htm 所述。
您必须将 exec
替换为 eval
才能使您的脚本正常工作,或者如@Jonathan Leffler 在评论中所建议的那样,您可以使用 bash -c "$cmd"
.
在 shell 中,“简单命令”是一系列可选的变量赋值和重定向,顺序任意,可选地后跟单词和重定向,由控制运算符终止。 (参见 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01), while a pipeline is a sequence of one or more commands separated by the control operator '|' (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02)。当 shell 看到行 exec $cmd
时,它没有看到控制运算符 |
,所以这是一个简单的命令。 (这与 exec
无关,任何命令都会发生相同的行为。)然后扩展行中的变量并遵循规则 the first field shall be considered the command name and remaining fields are the arguments for the command
,因此调用 exec
有一堆论据。 exec
不会尝试将参数解释为 shell 运算符(也许您打算使用 eval
而不是 exec
),而只是将所有参数传递给 cat
.