I'm writing the following script and I found the argument is not passed to a function called. However, when in an individual shell I can archive this.
usage() { if [ -n "$error_mess" ]; then echo -e "$error_mess"; fi; echo -e "usage stamens too long to present" 1>&2; exit 1; }
while getopts ":f:" flag
do
case "${flag}" in
f) if [ -n "${OPTARG}" ] ; then file=${OPTARG} ; else error_mess='\033[1m\033[5mError: file cannot be empty\033[0m' | usage; fi;;
*) usage;;
esac
done
I tried to put error_mess section after usage when calling inside the switch statement, but this error message is still not printing out.
When tried directly in bash it is working (only when the first line is run). The code entered directly to shell was:
# To check syntax error
error_mess='\033[1m\033[5mError: file cannot be empty\033[0m' ; if [ -n "$error_mess" ]; then echo -e "$error_mess"; fi
# To check if it can be passed inside a function
usage() { if [ -n "$error_mess" ]; then echo -e "$error_mess"; fi; echo -e "usage statement" 1>&2; exit 1; } ; error_mess='\033[1m\033[5mError: file cannot be empty\033[0m' | usage
# To check if it can be nested in if statement
a=0; if [ $a = 1 ] ; then echo "$a" ; else error_mess='\033[1m\033[5mError: file cannot be empty\033[0m' | usage ; fi
If I'm not doing it right, how should I correct it? I have other use case that do not have an error_mess or is having a different error_mess.
error_mess='…' usage?usagefunction doesn't read input (it just uses a variable). Also, the pipe makes the commands run in different processes (at the same time), so the variable is getting set in a different process from where you're trying to use it.var=value | usageshould just bevar=value usage-- no|or other separator inbetween. But that's not passing an argument at all; an argument would beusage valueecho -e ...anything...is a bad idea; useprintf '%b\n' ...anything...instead. See the APPLICATION USAGE and RATIONALE sections of the POSIX standard forecho, and/or the excellent answer by Stephane on Why is printf better than echo? over on Unix & Linux.