Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

bash - whats the correct way to loop this

I have a script where inotifywait is piped into a while loop that executes the following logic.

     cp "$S3"/2/post2.png "$S3";
     mv "$S3"/1/post1.png "$S3"/2/post2.png;
     cp "$S3"/3/post3.png "$S3";
     mv "S3"/post2.png "$S3"/3/post3.png;

so forth and so on..... then at the end of the script...

     mv "$dir"/$file "$S3"/1/post1.png

That line represents a fresh post, the above is the rotation of older post.

I can can hand code the iterations all the way down to 100+, but I would like to program more efficiently and save time.

So, what's some correct ways to loop this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think a better mechanism would list the directories in "$S3" in reverse numeric order, and arrange to process them like that. It isn't clear if the 100 directories are all present or whether they need to be created. We'll assume that directories 1..100 might exist, and directory N will always and only contain postN.png.

I'm assuming that there are no spaces, newlines or other awkward characters in the file paths; this means that ls can be used without too much risk.

for dirnum in $(cd "$S3"; ls */*.png | sed 's%/.*%%' | sort -nr)
do
    next=$(($dirnum + 1))
    mv "$S3/$dirnum/post$dirnum.png" "$S3/$next/post$next.png"
done

The cd "$S3" means I don't get a possibly long pathname included in the output; the ls */*.png lists the files that exist; the sed removes the file name and slash, leaving just a list of directory numbers containing files; and the sort puts the directories in reverse numeric order.

The rest is straight-forward, given the assumption that the necessary directories already exist. It would not be hard to add [ -d "$S3/$next" ] || mkdir -p "$S3/$next" before moving the file. Clearly, after the loop you can use your final command:

mv "$dir/$file" "$S3/1/post1.png"

Note that I've enclosed complete names in double quotes; it generally leads to fewer nasty surprises if something acquires spaces unexpectedly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...