我有一个需要为其逻辑更改IFS的函数:
my_func() {
oldIFS=$IFS; IFS=.; var="$1"; arr=($var); IFS=$oldIFS
# more logic here
}
我可以在功能中声明IFS为local IFS
,这样我就不必担心支持其当前值并在以后恢复吗?
答案 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的变量(使用readonly
或declare -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.