Search code examples
bashshelllocalifs

Can IFS be changed locally in a Bash function?


I have a function that needs to change IFS for its logic:

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

Can I declare IFS as local IFS inside the function so that I don't need to worry about backing its current value and restore later?


Solution

  • It appears to work as you desire.

    #!/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|"
    

    This prints:

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