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 ./myscript.sh firstargument. What do the -n do?


The -n is a test for a non-empty string.

If the "$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.

The test utility is equivalent to [, but [ requires that the last argument is ].

The test could also be written as

while test -n "$1"; do

Both [ and test are likely built into your shell, but should also be available as external commands under a standard path like /bin.

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).

This -n test is also one of the standard tests and therefore also listed in the POSIX standard for the test utility.

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"

... depending on what the script does, obviously.

  • 4
    ... and the while is probably coupled to a shift inside the loop (which is why it would be used instead of if). – Stephen Kitt Jan 18 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.