bash:将所有参数视为单个字符串参数

时间:2019-03-24 14:49:53

标签: bash parameters

将通过一个示例对此进行更好的解释。我正在构建一个bash脚本,它每1秒重新运行传递的命令行。这是我的第一次尝试:

-文件wtbash

watch -n1 "$@"

如果我发出:

wt "df -h | grep sda"

可以。我希望能够做到:

wt df -h | grep sda

工作原理相同

也就是说,我想将“ df -h | grep sda”视为单个字符串参数

1 个答案:

答案 0 :(得分:1)

有一个 app 变量!来自man bash

   *      Expands to the positional parameters, starting from one.  When the expan‐
          sion is not within double quotes, each positional parameter expands to  a
          separate  word.   In contexts where it is performed, those words are sub‐
          ject to further word splitting and pathname expansion.  When  the  expan‐
          sion  occurs  within  double quotes, it expands to a single word with the
          value of each parameter separated by the first character of the IFS  spe‐
          cial  variable.   That  is, "$*" is equivalent to "$1c$2c...", where c is
          the first character of the value of the IFS variable.  If IFS  is  unset,
          the  parameters  are separated by spaces.  If IFS is null, the parameters
          are joined without intervening separators.

因此将您的脚本更改为:

#!/bin/bash

watch -n1 "$*"

但这不适用于管道。您仍然需要避开那些:

wt df -h \| grep sda