是否可以在Bash函数中本地更改IFS?

cod*_*ter 0 bash shell local ifs

我有一个功能需要为其逻辑更改IFS:

my_func() {
  oldIFS=$IFS; IFS=.; var="$1"; arr=($var); IFS=$oldIFS
  # more logic here
}
Run Code Online (Sandbox Code Playgroud)

我可以将IFS声明为local IFS函数内部的内容,这样就不必担心备份其当前值并在以后还原吗?

Ini*_*ian 5

是的,它可以被定义!

只要你定义了它local,函数中值的设置就不会影响全局IFS值。请参阅下面的片段之间的区别

addNumbers () {
    local IFS='+'
    printf "%s\n" "$(( $* ))"
}
Run Code Online (Sandbox Code Playgroud)

当在命令行中调用时,

addNumbers 1 2 3 4 5 100
115
Run Code Online (Sandbox Code Playgroud)

和做

nos=(1 2 3 4 5 100)
echo "${nos[*]}"
Run Code Online (Sandbox Code Playgroud)

从命令行。hexdump上面的输出echo不会显示IFS函数中定义的值

echo "${nos[*]}" | hexdump -c
0000000   1       2       3       4       5       1   0   0  \n
000000e
Run Code Online (Sandbox Code Playgroud)

请参阅我的答案之一,我如何使用本地化IFS来进行算术 - How can I add numeric in a bash script


Bar*_*mar 5

它似乎按您的意愿工作。

#!/bin/bash
changeIFSlocal() {
    local IFS=.
    echo "During local: |$IFS|"
}
changeIFSglobal() {
    IFS=.
    echo "During global: |$IFS|"
}
echo "Before: |$IFS|"
changeIFSlocal
echo "After local: |$IFS|"
changeIFSglobal
echo "After global: |$IFS|"
Run Code Online (Sandbox Code Playgroud)

打印:

Before: |
|
During local: |.|
After local: |
|
During global: |.|
After global: |.|
Run Code Online (Sandbox Code Playgroud)