首页 > 解决方案 > 打印由空格以外的分隔符分隔的函数参数

问题描述

我需要使用非标准分隔符打印参数的函数(而不是由创建的空格my_func() { echo "$@"; })。像这样的东西:

$ my_func foo bar baz
foo;bar;baz

参数的数量各不相同,我不需要尾随分隔符。有任何想法吗?

标签: bash

解决方案


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


推荐阅读