简体   繁体   English

在脚本中使用 for,Ubuntu 命令行

[英]Using for in a Script, Ubuntu command line

How can I pass each one of my repository files and to do something with them?如何传递我的每个存储库文件并对其进行处理?

For instance, I want to make a script:例如,我想制作一个脚本:

#!/bin/bash
cd /myself
#for-loop that will select one by one all the files in /myself
#for each X file I will do this:
tar -cvfz X.tar.gz /myself2

So a for loop in bash is similar to python's model (or maybe the other way around?).所以 bash 中的 for 循环类似于 python 的 model (或者可能反过来?)。

The model goes "for instance in list": model “例如在列表中”:

for some_instance in "${MY_ARRAY[@]}"; do
    echo "doing something with $some_instance"
done

To get a list of files in a directory, the quick and dirty way is to parse the output of ls and slurp it into an array, a-la array=($(ls)) To quick explain what's going on here to the best of my knowledge, assigning a variable to a space-delimited string surrounded with parens splits the string and turns it into a list.要获取目录中的文件列表,快速而肮脏的方法是解析ls的 output 并将其放入数组中,a-la array=($(ls))快速解释这里发生的事情最好据我所知,将变量分配给用括号括起来的以空格分隔的字符串会拆分字符串并将其转换为列表。

Downside of parsing ls is that it doesn't take into account files with spaces in their names.解析ls的缺点是它不考虑名称中带有空格的文件。 For that, I'll leave you with a link to turning a directory's contents into an array , the same place I lovingly:) ripped off the original array=($(ls -d */)) command.为此,我将为您提供将目录内容转换为数组的链接,这也是我非常喜欢的地方:) 撕掉了原始的array=($(ls -d */))命令。

you can use while loop, as it will take care of whole lines that include spaces as well:您可以使用while循环,因为它会处理包含空格的整行:

#!/bin/bash
cd /myself
ls|while read f
do
tar -cvfz "$f.tar.gz" "$f"
done

you can try this way also.你也可以试试这个方法。

for i in $(ls /myself/*)对于我在 $(ls /myself/*)

do

tar -cvfz $f.tar.gz /myfile2焦油 -cvfz $f.tar.gz /myfile2

done完毕

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

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