1
\$\begingroup\$

Is there a more efficient way to run this? I am especially interested in a way which perhaps does not require a for loop...

shopt -s nullglob

file=
declare -a ARRAY1
ARRAY1=( ~lettus_*.sh )
for file in ${ARRAY1[@]}
do
    ##
    ## Get <name> from /some/path/lettus_name.sh
    ##

    # remove .sh extension
    file=${file%.sh}

    #  remove full path up to and including lettus_
    file=${file//*lettus_}

    echo $file
done

shopt -u nullglob
\$\endgroup\$
4
\$\begingroup\$
  1. I'm assuming that file=${file//*lettus_} is supposed to be file=${file##*lettus_}.

  2. Don't do file=. There is no reason to declare the file variable before-hand. Using it is a the loop variable automatically creates it.

  3. Get rid of the temporary ARRAY1 variable (which fyi is not a good variable name). Just do for file in lettus_*.sh. In fact, since you don't quote ${ARRAY1[@]}, word-splitting would make your program fail in some cases.

  4. Why do you want a more efficient way? This should run in a split-second unless you have a million files.

\$\endgroup\$
  • \$\begingroup\$ Yes. Need to change to file=${file##*lettus_}. Thanks. And you are right, it will be very fast. I just thought I was perhaps scripting this naively..... \$\endgroup\$ – Felipe Alvarez Jan 12 '16 at 2:23
  • 1
    \$\begingroup\$ Well "naively" doesn't just have to do with performance. All programming -- even "simple" shell scripting -- is a trade-off among many competing factors, two of which are speed and code clarity. In most cases, clarity wins out :) \$\endgroup\$ – gardenhead Jan 12 '16 at 2:43

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.