I have a shell script with while loop starting with
while [ -n "$1" ]; do
I know that
$1 refers to the argument right after the name of the script, ie
firstargument, when I execute
What do the
-n is a test for a non-empty string.
"$1" expands to an empty string, then that particular test fails and the loop will not execute.
It is likely that the body of the loop contains a
shift statement to shift the next positional parameter into
$1, and that the loop in this way loops over the arguments to the script, until it finds an empty argument or comes to the end of the list of arguments.
test utility is equivalent to
[ requires that the last argument is
The test could also be written as
while test -n "$1"; do
test are likely built into your shell, but should also be available as external commands under a standard path like
You will be able to read more about this and other tests in
man test, as well as in the manual for your shell (as it's a built-in utility).
-n test is also one of the standard tests and therefore also listed in the POSIX standard for the
If this loop is supposed to loop over all arguments of the shell script, than it may be failing to do so if an argument is empty:
$ sh -c 'while [ -n "$1" ]; do printf "arg: %s\n" "$1"; shift; done' sh 1 2 3 "" 4 5 6 arg: 1 arg: 2 arg: 3
Instead, it should possibly use something like
for arg do if [ -n "$arg" ]; then # do something with "$arg" fi done
... depending on what the script does, obviously.