首页 > 解决方案 > /bin/sh Adding an element to the arguments array from within the script

问题描述

Ultimate Goal

Essentially I have a while loop going through each command-line argument passed to the script, but want to set default behaviour if no arguments are passed.

Current solution idea

My plan for this is to test if there are any arguments prior to this while loop and if there aren't any, simply add the default arguments (flags in this case) to the argument array and let the script execute from there as normal.

Problem I'm having

Where I'm tripping up a little here is figuring out the syntax to add these default arguments to the arguments array itself (I can get values from it no problem).

This is what I have so far:

if test $# -eq 0
then
    # ADD --default TO ARGUMENTS ARRAY HERE
fi

while test $# -gt 0
do
    case "$1" in
  --opt1) DO STUFF
        ;;
  --opt2) DO MORE / OTHER STUFF
        ;;
  --default) DO DEFAULT STUFF
       ;;
    esac
    shift
done

Following and altering examples using user-defined arrays I have tried:

if test $# -eq 0
then
    $+=('--default')
fi

But just get the syntax error

syntax error near unexpected token `'--default''

标签: sh

解决方案


sh does not have arrays other than the built-in command-line argument list, and thus no += operator for arrays.

You also seem to be missing a character; what you wrote evaluates to assigning (default) to the value of the variable $+ but this variable is not valid (though because there are no arrays, the parentheses cause an error already).

The shell allows you to use set to manipulate the built-in argument list.

if test $# -eq 0
then
    set -- --default
fi

The condition requires the array to be empty, so we simply populate it with the single element you provided; in the general case, you could add stuff to the end with

set -- "$@" --default

or correspondingly to the beginning by putting something before "$@" (which of course contains the previous value of the argument list).


推荐阅读