shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

Warn about naive saving and restoration of IFS

Open NateEag opened this issue 4 years ago • 0 comments

For new checks and feature suggestions

  • [X] https://www.shellcheck.net/ (i.e. the latest commit) currently gives no useful warnings about this
  • [X] I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related

Here's a snippet or screenshot that shows the problem:


#! /bin/bash

PREV_IFS="$IFS"
IFS=";"
test="1;2;3"
for foo in $test; do
    echo "$foo"
done
IFS="$PREV_IFS"

Here's what shellcheck currently says:

No issues detected!

Here's what I wanted or expected to see:

Saving IFS then restoring its value directly as above can yield unexpected results.

Specifically, if IFS was unset before that snippet, IFS winds up being set to an empty string afterwards. When IFS is not set, POSIX says word splitting behaves as though it were set to ' \t\n', whereas if it is set to empty string, word splitting is not performed.

Since that's unlikely to be what the developer wants, it would be great if shellcheck warned about this idiom.

Corrected versions of this idiom can be found here:

https://unix.stackexchange.com/a/640063

NateEag avatar Feb 26 '22 02:02 NateEag