I am having difficulty trying to get an if statement working inside a function. I am using a very simple example like below to echo the $1 variable after script execution:
Logic inside script
STATUS() {
if [[ $1 == "-s" ]];then
echo "--------------------------------------------------------"
echo "Test success at: `date`:"
echo "--------------------------------------------------------"
else
echo "--------------------------------------------------------"
echo "Test fail at: `date`:"
echo "--------------------------------------------------------"
fi
}
STATUS
Example Execution:
ksh chris_test.sh -s
Expected Output:
--------------------------------------------------------
Test success at: Sun Jan 7 06:59:34 GMT 2024:
--------------------------------------------------------
What I am getting:
--------------------------------------------------------
Test fail at: Sun Jan 7 06:59:34 GMT 2024:
--------------------------------------------------------
I have attempted to escape the double quotes and the dollar sign, including the square brackets even trying to make square brackets single makes no difference. Still seeing fail. Where am I going wrong here?
Inside of
STATUS(),$1does not refer to the script's first argument but to the function's. When you call the function you'll need to forward the script's arguments so it can read them."$@"does that. It expands to"$1" "$2" "$3" ...for however many arguments there are, and with them properly quoted so spaces and other special characters are retained.