首页 > 解决方案 > 如何使用像 $1 或 $2 或 $3 这样的单个 bash 命令作为文本字符串而不是一个单词?

问题描述

如何使用 bashrc 命令,如下所示

  # .bashrc file
  # google_speech
  say () {
    google_speech -l en "$1"
  }

作为一串文本,因为上面的代码只读出了我粘贴的句子或段落的第一个单词。

例如,如果我进入终端并输入:

  $ say hello friends how are you

然后脚本只认为我输入了

  $ say hello

标签: bashvariablesargs

解决方案


尝试使用"$@"(带双引号)来获取函数的所有参数:

$ declare -f mysearch # Showing the definition of mysearch (provided by your .bashrc)
mysearch () 
{ 
    echo "Searching with keywords : $@"
}
$ mysearch foo bar # execution result
Searching with keywords : foo bar

函数或脚本参数类似于数组,因此您可以使用:

1)$#/${#array[@]}获取参数/数组元素的数量。

2)$1/${array[1]}获取第一个参数/数组的元素。

3)$@/${array[@]}获取所有参数/数组的元素。

编辑:根据chepner的评论:

在较大的字符串中使用 $@ 有时会产生意想不到的结果。这里的目的是产生一个单词,所以最好使用 $*

这是一个很好的话题,有很好的答案来解释这些差异。

编辑 2:不要忘记在$@or周围加上双引号$*,也许你google_speach只使用一个 arg。这是一个演示,可以让您更好地理解:

$ mysearch ()  {      echo "Searching with keywords : $1"; }
$ mysearch2 ()  {     mysearch "$*"; }
$ mysearch2 Hello my dear
Searching with keywords : Hello my dear
$ mysearch3 ()  {     mysearch $*; } # missing double quotes
$ mysearch3 Hello my dear
Searching with keywords : Hello # the other arguments are at least ignored (or sometimes the program will fail when he's controlling the args).

推荐阅读