我正在尝试用循环删除一些文件。但不知道该怎么做。以下是我想做的事情:
#!/bin/bash
dir1=/path/to/file
dir2=/path/to/file
dir3=/path/to/file
for i in 1 2 3
do
rm ${dir$i}
done
答案1
这是可能的eval
,但我强烈建议不要使用它!
使用数组来代替:
dirs=(
"/path/to/file1"
"/path/to/file2"
"/path/to/file3"
)
for i in 0 1 2
do
rm "${dirs[$i]}"
done
# OR simply loop all the array values:
for dir in "${dirs[@]}"
do
rm "$dir"
done
请注意,数组是以 0 为基础的。
答案2
你可以在 bash 中使用间接
If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new pa‐ rameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion.
但它需要一个中间变量,例如:
dir1=/path/to/file1
dir2=/path/to/file2
dir3=/path/to/file3
然后
$ for i in 1 2 3; do d=dir$i; echo rm "${!d}"; done
rm /path/to/file1
rm /path/to/file2
rm /path/to/file3
dir1
dir2
dir3
您可以通过使用括号扩展循环字符串来消除中间变量:
for d in dir{1..3}; do echo rm "${!d}"; done
zsh
使用修饰符可以实现同样的功能P
:
% for i in 1 2 3; do d=dir$i; echo rm ${(P)d}; done