r0skar
r0skar

Reputation: 8696

Bash Script + Shift Multiple Variables

I have created a simple bash script on Linux to create random files. I pass the filenames and filesize to the script like this:

./createFiles 5 filename1 filename2

*5 = filesize

My code looks like this:

#! /bin/bash

oriDir=files/ori
fileSize=$1
fileName=$2


# Create files
for fileName do

    dd if=/dev/urandom of=$oriDir/$2.mp4 bs=1048576 count=$fileSize

    # Shift through filenames
    shift 1

done

The output is as expected. 2 new files in my dir:

filename1.mp4 (size 5)
filename2.mp4 (size 5)

What I would to to do now is to use various filesizes foreach filename. My command would than look something like this:

./createFiles 5 2 filename1 filename2

The script would than generate 2 files:

filename1.mp4 (size 5)
filename2.mp4 (size 2)

Optionally, the script should be able to do the following: in case there are more filenames than given filesizes, it should just take the last filesize for all remaining filenames:

./createFiles 5 2 filename1 filename2 filename3

would generate:

filename1.mp4 (size 5)
filename2.mp4 (size 2)
filename3.mp4 (size 2)

I did try to play around with shift and add another shit command, but nothing worked.

Upvotes: 1

Views: 6651

Answers (1)

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

if you choose something like this

./script file1 size1 file2 size2 ... fileN sizeN

you can iterate over the this list in pairs

limit=$[ $#/2 ]; 
for((i=0;i<$limit;i++)){
file=$1 
size=$2

# do some stuff
shift 2
} 

Upvotes: 5

Related Questions