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

时间:2018-06-06 20:16:35

标签: bash shell local ifs

我有一个需要为其逻辑更改IFS的函数:

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

我可以在功能中声明IFS为local IFS,这样我就不必担心支持其当前值并在以后恢复吗?

4 个答案:

答案 0 :(得分:3)

它似乎可以按你的意愿运作。

#!/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: |.|

答案 1 :(得分:2)

是的,可以定义!

只要您定义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[*]}"
从命令行

。上述hexdump输出中的echo不会显示函数中定义的IFS

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

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

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:0)

我感到困惑,因为我在函数内部将IFS的值更改为:(不使用local),然后在调用函数后尝试使用此命令显示IFS的值: / p>

echo $IFS

显示一条空行,让我感觉功能没有改变IFS。在发布问题后,我意识到单词分裂正在发挥作用,我应该使用

echo "$IFS"

printf '%s\n' "$IFS"

或者,甚至更好

set | grep -w IFS=

准确显示IFS值。

回到局部变量的主题,是的,任何变量都可以在函数内声明为local以限制范围,除了已经声明为readonly的变量(使用readonlydeclare -r内置命令)。这包括Bash internal变量,如BASH_VERSINFO等。

来自help local

  

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.