简体   繁体   English

Bash 脚本 + Shift 多个变量

[英]Bash Script + Shift Multiple Variables

I have created a simple bash script on Linux to create random files.我在 Linux 上创建了一个简单的 bash 脚本来创建随机文件。 I pass the filenames and filesize to the script like this:我将文件名和文件大小传递给脚本,如下所示:

./createFiles 5 filename1 filename2

*5 = filesize *5 = 文件大小

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:我的目录中有 2 个新文件:

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:该脚本将生成 2 个文件:

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.我确实尝试过使用 shift 并添加另一个狗屎命令,但没有任何效果。

if you choose something like this如果你选择这样的东西

./script file1 size1 file2 size2 ... fileN sizeN ./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
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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