【发布时间】:2020-08-12 09:03:36
【问题描述】:
如何传递我的每个存储库文件并对其进行处理?
例如,我想做一个脚本:
#!/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
【问题讨论】:
如何传递我的每个存储库文件并对其进行处理?
例如,我想做一个脚本:
#!/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
【问题讨论】:
所以 bash 中的 for 循环类似于 python 的模型(或者可能反过来?)。
模型进入“例如在列表中”:
for some_instance in "${MY_ARRAY[@]}"; do
echo "doing something with $some_instance"
done
要获取目录中的文件列表,快速而肮脏的方法是解析ls 的输出并将其放入数组中,a-la array=($(ls))
据我所知,为了快速解释这里发生的事情,将变量分配给用括号括起来的空格分隔的字符串会拆分字符串并将其转换为列表。
解析 ls 的缺点是它不考虑名称中带有空格的文件。为此,我会留给你一个 link to turning a directory's contents into an array,我很喜欢这个地方 :) 撕掉了原来的 array=($(ls -d */)) 命令。
【讨论】:
for i in "${array=($(ls))"; do tar -cvfz "$i.tar.gz" done,但它不起作用:o 即使我将 tar -cvfz i.tar.gz 更改为 echo $i,它也不会打印任何内容
array=($(ls)) 应该排在前面;它创建了一个名为“array”的变量,可以在你的 for 循环中访问,如 for i in "${array[@]}"
您可以使用while 循环,因为它会处理包含空格的整行:
#!/bin/bash
cd /myself
ls|while read f
do
tar -cvfz "$f.tar.gz" "$f"
done
【讨论】:
你也可以试试这个方法。
for i in $(ls /myself/*)
做
tar -cvfz $f.tar.gz /myfile2
完成
【讨论】: