files=rm file1.txt
...运行file1.txt
与环境变量files
设置为值rm
的命令。
这通常是任何简单命令前面有KEY=VALUE
对这些对被视为环境变量,仅在该命令的持续时间内设置。
也许你不是想:
files=file1.txt
...或:
files=() # create an empty array, not a scalar (string) variable.
read number
case $number in
1) files+=(file1.txt) ;; # or simply: 1) rm file1.txt ;;
2) files+=(file2.txt) ;; # or simply: 2) rm file2.txt ;;
3) files+=(file3.txt) ;; # or simply: 3) rm file3.txt ;;
*) echo "This file does not exist" >&2 ; exit 1;;
esac
# ...if collecting filenames in an array, then...
echo "Removing files:" >&2
printf ' %q\n' "${files[@]}" >&2 # ...expand that array like so.
rm -f "${files[@]}" # likewise
要理解为什么像cmd='rm file1.txt'
将是 - 而正确的语法 - 很不好的做法,并开放自己的错误,见BashFAQ #50。
顺便说一句,使用名为'files'的标量变量来存储(大概)一个*列表*文件是坏的。标量本质上只能存储一个值;如果您依赖于能够将空间上的值分割以获取文件名列表,那么在尝试使用名称中包含空格的文件时会感到非常失望。 –
......作为读者,我不清楚为什么你的脚本中有一个'files'变量。为什么不直接运行删除? –
我把这个标记为重复的问题不是*完全* on-point本身,而是接受的答案直接解决了这个问题。 –