简体   繁体   中英

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.

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
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM