0
\$\begingroup\$

Have been constructing an array that can be used to populate options to find. ${incl[@]} made from function parameter arguments that takes filename suffixes.

# get parameter arguments
("--incl")
  incl+=("$2") ; shift 2 ;;  # file type suffix

Example using --incl .texi --incl .org gives incl=( .texi .org ).

But I also have the option for the user to pass a delimiter called fs, so one can use --incl .texi,.org by using --fs ",". This means that if fs is specified, I would need to split each element of array incl.

But I believe there is repetition in the code and possible fails in some circumstances. It could need some cleaning up, and need suggestions and analysis.

  if [[ -z "$fs" ]]; then  # undefined field separator

    isufx=( '(' )
    for ext in "${incl[@]}"; do
      isufx+=( -name "*$ext" -o )    # for find cmd
    done
    isufx[${#isufx[@]}-1]=')'  # modify last -o with )
  
  else

    isufx=( '(' )

    for ext in "${incl[@]}"; do

      if [[ "$ext" == *"$fs"* ]]; then
        s=${ext//"$fs"/" "}
        for fltyp in $s; do
          isufx+=( -name "*$fltyp" -o )  # for find cmd
        done
      else
        isufx+=( -name "*$ext" -o )  # for find cmd
      fi

    done

    isufx[${#isufx[@]}-1]=')'  # modify last -o with )

  fi 
\$\endgroup\$
1
  • \$\begingroup\$ Is this a good way for an if condition [[ -z "$fs" && "$ext" == *"$fs"* ]]. If I remember, one can also introduce parentheses. So it becomes [[ (-z "$fs") && ("$ext" == *"$fs"*) ]]. \$\endgroup\$
    – Pietru
    Commented Jul 31, 2021 at 14:19

1 Answer 1

1
\$\begingroup\$

The code the variable s that splits according to the value of fs. A more compact implementation is to use the variable s, then decide whether to split tho value of s, or not.

Thus, the following code

  isufx=( '(' )

  for ext in "${incl[@]}"; do

    s="$ext"
    [[ ! -z "$fs" && "$ext" == *"$fs"* ]] && s=${ext//"$fs"/" "}
    for fltyp in $s; do
      isufx+=( -name "*$fltyp" -o )   # options for find cmd
    done

  done

  isufx[${#isufx[@]}-1]=')'  # modify last -o with )

  if (( vb >= 2 )); then
    echo "isufx[*]: ${isufx[*]}"  
  fi
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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