I have thi开发者_StackOverflow中文版s
USAGE="Usage: -f [file name] -c [column] -v [value] ."
while getopts ":f:c:v: " OPTIONS; do
case $OPTIONS in
f ) file=$OPTARG;;
c ) column=$OPTARG;;
v ) value=$OPTARG;;
h ) echo $USAGE;;
\? ) echo $USAGE
exit 1;;
* ) echo $USAGE
exit 1;;
esac
done
the filename is fun2.sh ... I want to echo the $USAGE if they fail to put a parameter in -f or -c or -v.
I have tryied putting a
" ") echo $USAGE
exit1;;
but that didn't work..
I also tried
if [ $file || $column || $value == "" ]
echo $USAGE
but then again it didn't work..
Any Help would be appreciated
EDIT
What worked for me
if [ "$file" == "" ] ;
then
echo $USAGE
elif [ "$column" == "" ];
then
echo $USAGE
elif [ "$value" == "" ];
then
echo $USAGE
else
show_column
check_temp
file_move
write_file
Try:
[[ -z "$file" || -z "$column" || -z "$value" ]] && echo "$USAGE" && exit
You can't do this in the loop. Check the values of the variables after the loop and print $USAGE
if they are empty or the values are wrong (not an integer, for example).
Not entirely sure why your code doesn't work, but this should:
USAGE="Usage: -f [file name] -c [column] -v [value] ."
params="$(getopt -o f:c:v:h --name "$(basename -- "$0")" -- "$@")"
if [ $? -ne 0 ]
then
echo "$USAGE"
exit 1
fi
eval set -- "$params"
while true
do
case $1 in
-f)
file="$2"
shift 2
;;
-c)
column="$2"
shift 2
;;
-v)
value="$2"
shift 2
;;
-h)
echo "$USAGE"
exit
;;
--)
shift
break
;;
*)
echo "$USAGE"
exit 1
;;
esac
done
John, i dont understand what is a bad with your code: In my bash got the following: (the name of script is "go") - OK mean, got what i expected.
jonatan:shell clt$ ./go
#ok
jonatan:shell clt$ ./go ewdwedw
#ok
jonatan:shell clt$ ./go -a
Usage: -f [file name] -c [column] -v [value] .
#ok, -a is incorrect
jonatan:shell clt$ ./go -f
Usage: -f [file name] -c [column] -v [value] .
#ok, -f need an argument
jonatan:shell clt$ ./go -f aaa
#ok, -f has an argiment
jonatan:shell clt$ ./go -c
Usage: -f [file name] -c [column] -v [value] .
jonatan:shell clt$ ./go -c -v
#hm - "-v" comes into `column`, so syntactically is ok, but ....
Therefore you need another check - as you done already. So, your script is OK.
Here is my "go".
#!/bin/bash
USAGE="Usage: -f [file name] -c [column] -v [value] ."
while getopts ":f:c:v:" OPTIONS; do
case "$OPTIONS" in
f ) file=$OPTARG;;
c ) column=$OPTARG;;
v ) value=$OPTARG;;
h ) echo $USAGE;;
\? ) echo $USAGE; exit 1;;
* ) echo $USAGE; exit 1;;
esac
done
精彩评论