Reputation: 13
This KSH code working fine on AIX and RH with the standard IFS (default)
[ "$(uname)" = "AIX" ] && ECHO="echo" || ECHO="echo -e"
echo "AA BB CC DD" | while read a b c d; do
[ "`$ECHO $a | cut -c1-2`" = "AA" ] && echo $b
done
If i set a different IFS like a ; for example
[ "$(uname)" = "AIX" ] && ECHO="echo" || ECHO="echo -e"
IFS=";"
echo "AA;BB;CC;DD" | while read a b c d; do
[ "`$ECHO $a | cut -c1-2`" = "AA" ] && echo $b
done
I get an error like only on RH not Aix
+ echo 'AA;BB;CC;DD'
+ read a b c d
+ cut -c1-2
+ 'echo -e' AA
-ksh: line 3: echo -e: not found
+ [ '' '=' AA ]
+ read a b c d
+ echo .....
+ cut -d. -f1
Someone can explain me why this is happening and how we can solved it without a eval ? Thanks for your time :-)
Upvotes: 0
Views: 198
Reputation: 246877
You have ECHO="echo -e"
, then you set IFS=";"
, so when you expand $ECHO unquoted (where globbing and word splitting will take effect), you get echo -e
as a single word (because you are word splitting using semicolon not whitespace), and of course there's no such command.
You'll want to refer to I'm trying to put a command in a variable, but the complex cases always fail. The answer is to use an array:
[ "$(uname)" = "AIX" ] && ECHO=(echo) || ECHO=(echo -e)
And then, use it like
"${ECHO[@]}" "$a" | cut -c1-2
You'll also need to use quotes more. Refer to Security implications of forgetting to quote a variable in bash/POSIX shells
(todo: discuss not using "echo -e"...)
Upvotes: 2