Issue
this is some bash code I wrote to check for an existing directory and make it if it didn't exist. It seems a bit clunky to me, so I'm wondering if people have tips??
dir_check () {
# this is a function for checking if a simulation directory exists and if
for i in $@
do
vers_num=1
# echo "$i \n"
if [ -d "$i" ]; then
if [ -d "$i-run-$vers_num" ]; then
while [ -d "$i-run-$vers_num" ]; do
((vers_num++))
new_dir="$i-run-$vers_num"
done
else
new_dir="$i-run-$vers_num"
fi
mkdir "$new_dir"
echo "$new_dir created"
else
mkdir $i
echo "$i created"
fi
done
}
just looking for feedback on this code
Solution
- use continue to shorten the logic
- calculate the next version with a pipeline
- if it doesn't exist, echo message and create
dir_check() {
for i in "$@"
do
test ! -d "$i" && { mkdir $i ; continue ; }
local ver=$( { ls -d "$i"-run-* 2>&- || echo 0; } | sed "s:$i-run-::" | sort -nr | head -1)
((ver++))
test ! -d "$i-run-$ver" && { mkdir "$i-run-$ver" ; echo "$i-run-$ver
created" ; }
done
}
Answered By - xpusostomos Answer Checked By - Marilyn (WPSolving Volunteer)