bash - 打印由空格以外的分隔符分隔的函数参数
问题描述
我需要使用非标准分隔符打印参数的函数(而不是由创建的空格my_func() { echo "$@"; }
)。像这样的东西:
$ my_func foo bar baz
foo;bar;baz
参数的数量各不相同,我不需要尾随分隔符。有任何想法吗?
解决方案
my_func() {
local IFS=';' # change the separator used by "$*", scoped to this function
printf '%s\n' "$*" # avoid reliability issues innate to echo
}
...或者...
my_func() {
local dest # declare dest local
printf -v dest '%s;' "$@" # populate it with arguments trailed by semicolons
printf '%s\n' "${dest%;}" # print the string with the last semicolon removed
}
关于“固有的可靠性问题”——请参阅POSIX 规范echo
的 APPLICATION USAGE 部分,并注意 bash 与该标准的一致性随编译时和运行时配置而变化。echo
推荐阅读
- swift - 一个常量序列可以使用for-in循环进行迭代,但不能直接调用next()?
- ruby - 如何防止ruby 2.7中的警告
- python - 如何从连接到 S3 存储桶的 SNS 中获取文件密钥
- c - SO_TIMESTAMP 套接字选项使用哪个时钟?
- ansible - 用于重启 Docker Swarm 服务的 Ansible 处理程序
- react-native - Flatlist 覆盖以前的数据
- reactjs - 部署到 GitHub 的 React 应用程序给了我一个缩小的错误 #152
- php - php mysql 与 pdo 连接失败
- python - Python/Tkinter -
- javascript - 如何使用evaluateJavaScript 将数据从WKWebview 发送到HTML 文件| iOS | Objective-C