0

I am writing a shell script that takes several args like -l -s -a -f thing ming and append only those starting with -.

This is my code:

arrayOfArgs=() 
for arg in "$@":
do
    case arg in 
    -*) arrayofArgs+=($args) ;;
    esac
 done

Now my arrayOfArgs print this

-l, -s, -a, -f.

The thing I am worried about is that the result is separated by the comma.

is ls {"$arrayOfArgs"} equivalent to ls -l -s -a -f ?

closed as unclear what you're asking by muru, Kiwy, Jeff Schaller, Archemar, Christopher Apr 23 '18 at 13:07

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • The commas will mess it up. Have you tried piping it into awk -F , '{print $1$2$3$4}'? That will ouput -l -s -a -f. – Nasir Riley Apr 23 '18 at 3:07
  • 6
    arrayofArgs+=($args) ;; ... there is not args variable, and you haven't shown us how you printed arrayofArgs, so there's no telling how the comma got there. Please show us what you're actually running. – muru Apr 23 '18 at 3:28
  • @muru when I print an array, it is empty. – Samun Apr 23 '18 at 4:35
  • Of course it's empty. You read the command line into arg but assign the array from args (so you basically assign empty values to arrayofArgs. – nohillside Apr 23 '18 at 6:01
1

Rather than trying to solve the question you've asked, this answer offers a solution that attempts to solve the underlying issue. For this example I've assumed that arguments a and s are booleans (switches) but argument l takes a parameter:

unset -v flagA flagS valueL
while getopts "al:s" OPT
do
    case "$OPT" in
        a)    echo "Got a"; flagA=true ;;
        s)    echo "Got s"; flagS=true ;;
        l)    printf 'Got l with value "%s"\n' "$OPTARG"; valueL="$OPTARG" ;;
    esac
done
shift "$((OPTIND - 1))"

printf '%s\n' "flagA=${flagA-unset}, flagS=${flagS-unset}, valueL=${valueL-unset}"
if [ "$#" -gt 0 ]; then
  printf 'Other arguments:\n'
  printf ' - "%s"\n' "$@"
fi

More information in the bash man page.

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