3
\$\begingroup\$

I wrote a pretty simple bash script. It takes a directory with subdirectories with incremental prefixes in their names (01test, 02test, 03test), creates a new directory with the next highest prefix and creates a couple of files and fills them with some default text.

I'd like to do this in fewer lines of code and eliminate redundancies.

#!/bin/bash
LAST=`exec ls example_dir | sed 's/\([0-9]\+\).*/1円/g' | sort -n | tail -1`
PREFIX="${LAST:0:2}"
PREFIX=$((PREFIX + 1))
PREFIX="$PREFIX"_
ARGS=$@
TESTNAME="${ARGS// /_}"
DIRNAME="example_dir/$PREFIX$TESTNAME"
mkdir $DIRNAME
mkdir $DIRNAME/some_directory
mkdir $DIRNAME/expected
touch $DIRNAME/first.txt
touch $DIRNAME/second.txt
touch $DIRNAME/third.json
echo "{" >> $DIRNAME/test.json
echo -e "\t\"enabled\": true" >> $DIRNAME/test.json
echo "}" >> $DIRNAME/test.json
echo "{" >> $DIRNAME/some_directory/$PREFIX.json
echo -e " \"entities\": [" >> $DIRNAME/some_directory/$PREFIX.json
echo " ]" >> $DIRNAME/some_directory/$PREFIX.json
echo "}" >> $DIRNAME/some_directory/$PREFIX.json
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Feb 9, 2016 at 0:18
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
  • tail must to read the whole file. Calling sort with a -r (aka --reverse option) you can use head instead.

  • touch takes multiple arguments. You may

    touch $DIRNAME/first.txt $DIRNAME/second.txt $DIRNAME/third.json
    

    and further use brace expansion:

    touch $DIRNAME/{first.txt,second.txt,third.json}
    
  • I would consider here-documenting the json files instead of echoing them, along the lines of:

    cat << EOF >> $DIRNAME/test.json
    {
     "enabled": true
    }
    EOF
    
answered Feb 9, 2016 at 0:51
\$\endgroup\$
1
  • \$\begingroup\$ isn't there a < missing? I think it has to look like: cat << EOF >> $DIRNAME/test.json \$\endgroup\$ Commented Jul 29, 2017 at 20:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.