bash - 如何使用像 $1 或 $2 或 $3 这样的单个 bash 命令作为文本字符串而不是一个单词?
问题描述
如何使用 bashrc 命令,如下所示
# .bashrc file
# google_speech
say () {
google_speech -l en "$1"
}
作为一串文本,因为上面的代码只读出了我粘贴的句子或段落的第一个单词。
例如,如果我进入终端并输入:
$ say hello friends how are you
然后脚本只认为我输入了
$ say hello
解决方案
尝试使用"$@"
(带双引号)来获取函数的所有参数:
$ 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).
推荐阅读
- php - Google 饼图未在 IE <= 8 中显示
- android - 有没有办法获取当前播放歌曲的信息?
- c# - 使用 asp-for 生成的查询字符串与同一模型上从 Url.Action 生成的查询字符串不匹配
- javascript - Codewars Kata 的问题 - 增加数组的最大差异
- python - 从列中提取数字并将每个拆分为单独的列
- mysql - 我在尝试更新列值 mysql 时遇到错误
- vue.js - Vuex 在操作中有条件地分配 null
- python - 通过检查列表中的元素类型,返回错误值
- node.js - 如何使用 mongoose 在 mongodb 中使用动态字段搜索数据?
- java - 如果通过 JarLauncher 启动 Spring-boot 会忽略 log4j2.xml