Reputation: 843
I am getting input from the user via command line and want to check if there is an input or not using the $@
the user invokes such as the following ways:
sh program <file1> <file2> ..
or
sh program < file1
in the script i am doing the following:
test -z "$@"
if test $? -eq 0
then
compute
else
do something..
fi
if the user invokes the program with a multiple lines, then i get an error from test -z "$@" saying that "test: too many arguments"
i tried to resolve this, but i am stuck. do you know how i can overcome this?
Upvotes: 0
Views: 343
Reputation: 21
$? is the shell exit status variable. If you want to check if the last command entered is executed in a true or false by returning 0 for true and non-zero values for other.
$# is the shell variable which show how many arguments does a user passed. And you can access those arguments with variables $0,$1 up to $9, where the $0 variable carries the command name, so you would be using starting $1.
Example.
if test $# -gt 0
then
echo "You pass $# Arguments";
echo "First Argument is : $1";
echo "Second Argument is : $2";
else
echo "You did not pass any Arguments";
fi
Upvotes: 0
Reputation: 312213
The problem is that given something like:
test -z "$@"
If the user runs your script with multiple arguments, this ends up being equivalent to:
test -z "arg1" "arg2" "arg3"
And that's why you're getting the "too many arguments" error. You should read the "Special Parameters" subsection of the "PARAMETERS" section of the bash(1)
man page for details. What you really want check is probably $#
, the number of arguments passed to your script:
if test $# -eq 0
then
compute
else
do something..
fi
But you can also test against $*
, which like $@
expands to the command line arguments but as a single string:
if test -z "$*"
then
compute
else
do something..
fi
Upvotes: 3
Reputation: 361919
$#
gives you the number of arguments.
if (($# > 0)); then
echo "passed $# arguments: $@"
else
echo "no arguments"
fi
Upvotes: 1