Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - Misunderstanding in how curly braces work in shell

I have a little bit of misunderstanding here. So, I execute these commands:

mkdir Week {1..13}
touch {1..13}.txt

mv {1..13}.txt Week {1..13}

My intention was to move 1.txt to Week 1, 2.txt to Week 2 and so on, but all files ended up in "Week 13" directory and I could not figure out how it works like that. Could anyone explain it to me if possible?


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

1 Answer

0 votes
by (71.8m points)

The curly braces are expanded in "brace expansion" (see man bash). So your last line is expanded to

 mv 1.txt 2.txt 3.txt ... 13.txt Week 1 Week 2 ... Week 13

If you look into man mv, you'll see

  mv [OPTION]... [-T] SOURCE DEST
  mv [OPTION]... SOURCE... DIRECTORY
  mv [OPTION]... -t DIRECTORY SOURCE...

It doesn't list anything like

mv [OPTION] SOURCE1 DEST1 SOURCE2 DEST2

You can use a loop to distribute the files into the directories:

for n in {1..13} ; do
    mv "$n".txt "Week $n"
done

If you aren't doing anything else with the files but creating them, you can in fact create them directly in the loop, so you don't need to create them in the same directory initially:

for n in {1..13} ; do
    mkdir "Week $n"
    touch "Week $n/$n.txt"
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...