A Better Way To Write this Bash Script?
This solution (listed below) works, but it doesn't look like the most practical of solutions. What I want to do is populate a folder with children with a name t_###_u and then fill those child directories with two files (one of which shoul开发者_如何学编程d be renamed to parent directory name and appended with a .c) Can anyone post a better, more elegant solution?
for i in {1..100}
do
mkdir `printf "t_%03d_u" $i`;
cp ./templates/* `printf "t_%03d_u" $i`;
mv `printf "./t_%03d_u/template.c" $i` `printf "./t_%03d_u/t_%03d.c" $i $i`;
done
echo "Did it work?"
Thanks for any help in advance.
The most obvious way to improve the script is to assign a variable to the name you use:
name=`printf "t_%03d" $i`
so then you can do
mkdir ${name}_u
cp ./templates/* ${name}_u/
mv ./${name}_u/template.c ./${name}_u/$name.c
seq -w
is hugely useful :)
#!/bin/bash
for i in `seq -w 1 100`
do
mkdir t_${i}_u
cp ./templates/* t_${i}_u
mv ./t_${i}_u/template.c ./t_${i}_u/t_${i}_u.c
done
echo "Did it work?"
I'm sure it could be improved a bit further with computing the name of the directory once and re-using it, but this is nicer-enough that I'm fine stopping here. :)
Bash 4.
for num in {001..100}
do
path="t_${num}_u"
mkdir "$path"
cp ./templates/* "$path";
mv $path/template.c ./$path/t_${num}.c
done
for i in $(seq -w 1 100); do
mkdir t_${i}_u
cp templates/* t_${i}_u
mv t_${i}_u/template.c t_${i}_u/t_${i}.c
done
haven't tested it.
You could save the result of the printf in a variable rather that re-doing it each time. Or just use seq -w 1 100
to generate the numbers:
for i in $(seq -w 1 100)
do
d=t_${i}_u
mkdir $d
cp templates/* $d
mv $d/template.c $d/t_$i.c
done
My only advice would be to set the zero padded string to a variable to ease reading:
for i in {1..100}
do
s=$(printf "%03d" $i)
mkdir t_${s}_u
cp ./templates/* t_${s}_u
mv ./t_${s}_u/template.c ./t_${s}_u/t_${s}.c
done
精彩评论