You need to use a variable's name in the for loop header. You used $file in your original question, i.e., the variable file's value.
You are also doing things a bit complicated. To run a command with a temporarily changed working directory, you may use a sub-shell.
( cd Em1 && month_range )
The working directory outside of the sub-shell is not affected by the cd inside the sub-shell. It's unclear what your cd_ret function is doing, so that's another possible source of errors. If you can't do it this way, for example, if month_range is setting variables that need to be visible in the original scope, then use
cd Em1 && { month_range; cd -; }
The above would cd into Em1, run the month_range function, and cd back, assuming month_range does not do further calls to cd. If month_range does use cd, then save the current working directory in a variable and use that instead.
wd=$PWD; cd Em1 && { month_range; cd "$wd"; }
The above assumes that month_range does not change or unset the wd variable.
Your use of awk is problematic as filenames on Unix technically may contain newline characters. It would be better to use a parameter substitution.
em=${file%%[.-]*}
The above chops off the value $file at first - or . character and assigns the resulting string to the variable em.
This leaves you with the following:
em1=first
em2=second
for file in *; do
em=${file%%[.-]*}
if [ "$em" = "$em1" ]; then
( cd Em1 && month_range )
elif [ "$em" = "$em2" ]; then
( cd Em2 && month_range )
else
echo 'Nothing to do'
fi
done
or
em1=first
em2=second
for file in *; do
em=${file%%[.-]*}
case $em in
"$em1") ( cd Em1 && month_range ) ;;
"$em2") ( cd Em2 && month_range ) ;;
*) echo 'Nothing to do'
esac
done
or, without extracting em from $file at all,
em1=first
em2=second
for file in *; do
case $file in
"$em1"[.-]*) ( cd Em1 && month_range ) ;;
"$em2"[.-]*) ( cd Em2 && month_range ) ;;
*) echo 'Nothing to do'
esac
done
or using bash syntax,
em1=first
em2=second
for file in *; do
if [[ $file == "$em1"[.-]* ]]; then
( cd Em1 && month_range )
elif [[ $file == "$em2"[.-]* ]]; then
( cd Em2 && month_range )
else
echo 'Nothing to do'
fi
done
If this then does what you intend depends on the month_range function or script.
$from theforstatement (for file in ...). If that's not the problem, I'd recommend puttingset -xbefore this section so it prints an execution trace -- inspect that and see if it differs from what you expect.cd_retwhich doesn't exist in the shown code. If it doesn't exist, that might be a problem. If you're just not showing it, then it's hard for any readers to check if there's a problem within it.