打印由空格以外的分隔符分隔的函数参数

Mac*_*zuk 3 bash

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

$ my_func foo bar baz
foo;bar;baz
Run Code Online (Sandbox Code Playgroud)

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

Cha*_*ffy 8

my_func() {
  local IFS=';'       # change the separator used by "$*", scoped to this function
  printf '%s\n' "$*"  # avoid reliability issues innate to echo
}
Run Code Online (Sandbox Code Playgroud)

...要么...

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
}
Run Code Online (Sandbox Code Playgroud)

关于"固有的可靠性问题echo" - 请参阅POSIX规范echo的"应用程序使用"部分,并注意bash与该标准的一致性因编译时运行时配置而异.

  • *在一行*中,你告诉shell在运行`printf`时将`IFS`放在环境中,而不是在生成printf的参数时扩展``$*'`.这与`(value ="foo"echo"$ value")`和`(value ="foo"; echo"$ value")`的不同之处是一样的.前者将变量放在`echo`的环境中,但echo在确定要发出的内容时不会查看其环境 - 它会查看其参数列表. (3认同)