snippetbashMinor
Bash script to create directories and files with a numbered prefix
Viewed 0 times
scriptprefixcreatewithnumberedfilesandbashdirectories
Problem
I wrote a pretty simple bash script. It takes a directory with subdirectories with incremental prefixes in their names (
I'd like to do this in fewer lines of code and eliminate redundancies.
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.jsonSolution
-
-
and further use brace expansion:
-
I would consider here-documenting the json files instead of echoing them, along the lines of:
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 maytouch $DIRNAME/first.txt $DIRNAME/second.txt $DIRNAME/third.jsonand 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 > $DIRNAME/test.json
{
"enabled": true
}
EOFCode Snippets
touch $DIRNAME/first.txt $DIRNAME/second.txt $DIRNAME/third.jsontouch $DIRNAME/{first.txt,second.txt,third.json}cat << EOF >> $DIRNAME/test.json
{
"enabled": true
}
EOFContext
StackExchange Code Review Q#119343, answer score: 3
Revisions (0)
No revisions yet.