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

3

我有一个需要更改IFS的函数,以适应其逻辑:

my_func() {
  oldIFS=$IFS; IFS=.; var="$1"; arr=($var); IFS=$oldIFS
  # more logic here
}

我是否可以在函数内部将IFS声明为local IFS,这样我就不必担心备份其当前值并稍后恢复了呢?


为什么不仅在调用函数时更改IFS的值?IFS=. my_func "some arg" - undefined
我不希望调用者承担这个责任,以便调用者和被调用者之间没有耦合。 - undefined
4个回答

12
看起来它按照你的要求工作。
#!/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|"

这将打印:

Before: |
|
During local: |.|
After local: |
|
During global: |.|
After global: |.|

5

是的,它可以被定义!

只要将其定义为 local,函数内的值设置不会影响全局的 IFS 值。请看下面片段之间的区别:

addNumbers () {
    local IFS='+'
    printf "%s\n" "$(( $* ))"
}

当在命令行中调用时,
addNumbers 1 2 3 4 5 100
115

并且执行

nos=(1 2 3 4 5 100)
echo "${nos[*]}"

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

echo "${nos[*]}" | hexdump -c
0000000   1       2       3       4       5       1   0   0  \n
000000e

请看我在其中一个回答中的使用本地化的 IFS 进行算术运算 - 如何在Bash脚本中添加数字


3

我因为在函数内部将 IFS 的值更改为 :(而没有使用 local)而感到困惑,然后尝试使用该命令显示 IFS 的值,在调用函数后:

echo $IFS

这段代码显示了一个空行,让我觉得函数似乎没有改变IFS。发帖后,我意识到这里发生了单词分割的情况,所以应该使用

echo "$IFS"

或者

printf '%s\n' "$IFS"

或者,更好的选择是:
set | grep -w IFS=

回到本文的主题,关于局部变量,是的,在函数内部可以将任何变量声明为local以限制其作用域,除了已经使用readonlydeclare -r内置命令声明为只读变量的变量。这包括Bash内部变量,如BASH_VERSINFO等。

来自help local

为了准确显示IFS值。

local: local [option] name[=value] ...

Define local variables.

Create a local variable called NAME, and give it VALUE.  OPTION can
be any option accepted by `declare'.

Local variables can only be used within a function; they are visible
only to the function where they are defined and its children.

Exit Status:
Returns success unless an invalid option is supplied, a variable
assignment error occurs, or the shell is not executing a function.

2

您可以将IFS指定为local变量;本地版本仍然用作字段分隔符字符串。

有时,在完全隔离的环境中运行函数是很有用的,这里没有任何更改是永久性的。(例如,如果函数需要更改shell选项。)这可以通过使函数在子shell中运行来实现;只需将函数定义中的{}更改为()

f() ( 
  shopt -s nullglob
  IFS=.
  # Commands to run in local environment
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接