'$? return different values in interactive vs in script

the following shell funciton when run interactively, the result is correct ($?=0):

-bash-4.2$ run_task ()
{
    echo "$(date) - ALGOX_INTRADAY_CURRENT_DIR=$ALGOX_INTRADAY_CURRENT_DIR";
    ls $ALGOX_INTRADAY_CURRENT_DIR/* 2> /dev/null;
    echo "$(date) - \$?=$?"
}
-bash-4.2$ ALGOX_INTRADAY_CURRENT_DIR=/apps/alcr-lnx/homes/sacimso/algox-intraday/current/
-bash-4.2$ run_task
Fri Feb 25 09:53:27 EST 2022 - ALGOX_INTRADAY_CURRENT_DIR=/apps/alcr-lnx/homes/sacimso/algox-intraday/current/
/apps/alcr-lnx/homes/sacimso/algox-intraday/current//req_CHILE-KFWD-759645_1645797825292802.xml
Fri Feb 25 09:53:27 EST 2022 - $?=0
-bash-4.2$

however, when run in a larger script, it reported no files was in the directory:

Fri Feb 25 09:49:44 EST 2022 - ALGOX_INTRADAY_CURRENT_DIR=/apps/alcr-lnx/homes/sacimso/algox-intraday/current/
Fri Feb 25 09:49:44 EST 2022 - $?=2

my understanding is $? is the return code of the immediate previous statement, the return code should be the same as long ALGOX_INTRADAY_CURRENT_DIR points to the same path. any idea why it yielded different result?



Solution 1:[1]

The issue was caused by spaces in file names. setting:

IFS=$(echo -en "\n\b")

resolved the issue

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 techie11