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

liwlm1x9  于 2023-08-07  发布在  Shell
关注(0)|答案(4)|浏览(100)

我有一个函数需要改变IFS的逻辑:

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

字符串
我可以在函数中将IFS声明为local IFS吗?这样我就不必担心备份它的当前值并在以后恢复。

vaqhlq81

vaqhlq811#

它似乎如你所愿。

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

vuktfyat

vuktfyat2#

可以定义!
只要定义了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来做算术的-How can I add numbers in a bash script

x8goxv8g

x8goxv8g3#

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

echo $IFS

字符串
它显示了一个空行,让我觉得函数没有改变IFS。在发布了这个问题之后,我意识到单词分裂在起作用,我应该使用

echo "$IFS"


或者是

printf '%s\n' "$IFS"


或者更好

set | grep -w IFS=


以准确显示IFS值。
回到局部变量的主题,是的,任何变量都可以在函数内声明为local以限制范围,除了已声明为只读的变量(使用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.

d4so4syb

d4so4syb4#

您可以将IFS指定为local变量;本地版本仍然用作字段分隔符字符串。
有时在完全隔离的环境中运行函数是很有用的,在这种环境中没有永久性的更改。(例如,如果函数需要更改shell选项。)这可以通过使函数在子shell中运行来实现;只需将函数定义中的{}更改为()

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

字符串

相关问题