0

My simple endeavour is as following: I have a couple of mp3 files in my home folder, let's say 0.mp3, 1.mp3, 2.mp3, 3.mp3. I want to use a bash script, let's say "merge.sh" to merge those files in one mp3 file, by using the contracted form of the cat command cat {0..3}.mp3 > total.mp3, but the two numbers shall be given as command line parameters, i.e.

bash merge.sh 0 3

Unfortunately, neither writing

cat {$1..$2}.mp3 > total.mp3

nor

cat {"$1".."$2"}.mp3 > total.mp3

works. In both cases the shell responds

"cat: {0..4}.mp3: No such file or directory"

If I explicitely put in those number in the script, i.e. write

cat {0..4}.mp3 > total.mp3,

then the script executes just fine. But why can't I hand this numbers over via command line parameters? What I am missing here?

Thanks in advance!

P.S: I am no bash script expert.

1 Answers1

0

Use a for loop to populate an array, then use the array.

for ((i=$1; i <= $2; i++)); do
  arr+=($i.mp3)
done

cat "${arr[@]}" > total.mp3

In fact, you can dispense with the array. It's a little less efficient, but for a reasonable number of files it shouldn't be noticeable.

for ((i=$1; i<=$2; i++)); do
  cat "$i.mp3"
done > total.mp3
chepner
  • 497,756
  • 71
  • 530
  • 681