-3

Please take a look at this code sample:

MIN=10

if [ -n "$1" ]; then echo "$1"; fi
if [ -n "$2" ]; then echo "$2"; fi 
if [ -n "$3" ]; then echo "$3"; fi
if [ -n "$4" ]; then echo "$4"; fi
if [ -n "$5" ]; then echo "$5"; fi
if [ -n "$6" ]; then echo "$6"; fi
if [ -n "$7" ]; then echo "$7"; fi
if [ -n "$8" ]; then echo "$8"; fi
if [ -n "$9" ]; then echo "$9"; fi
if [ -n "${10}" ]; then echo "${10}"; fi

echo "List of arguments: "$*"" 
echo "Name of this script: "$0""
if [ $# -lt "$MIN" ]; then echo "Not enough arguments, need $MIN to run."; fi

For example, the terminal output of $./new.sh q w e r t y u i o p will be:

q
w
e
r
t
y
u
i
o
p
List of arguments: q w e r t y u i o p
Name of this script: ./new.sh

And the output of $./new.sh q w e r t y u i o will be:

q
w
e
r
t
y
u
i
o
List of arguments: q w e r t y u i o
Name of this script: ./new.sh
Not enough arguments, need 10 to run.

Question: What does the -n mean?

3

[ is another name for the test builtin, see here and here, also this.

That sequence of if statements would probably be better off as a loop. In Bash we could use indirect expansion:

for ((i=1 ; i <= 10 ; i++)) ; do 
    if [ -n "${!i}" ] ; then 
        echo "${!i}"
    fi
done

The more common idiom would probably be to use shift on every iteration, but it destroys the argument list.

Also, quoting: here $0 is outside the quotes. In most cases its more useful to keep all variable expansions within quotes, unless you explicitly want word-splitting and filename expansion.

echo "Name of this script: "$0""

So, rather write:

echo "Name of this script: $0"
  • 1
    You can use shift inside a function and not affect the caller's argument list, though using a function just for that is obviously a bit hackish. – tripleee Jun 17 '17 at 16:56

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.