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:

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

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 ?

  • 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

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
    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" ;;
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' "$@"

More information in the bash man page.

|improve this answer|||||

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