我想找出一些文件名可能包含空格的文件的总大小:
cd /tmp
touch "a0 1"
touch "a1 1"
我将这些文件名放入变量并制作一个列表:
var0="/tmp/a0 1"
var1="/tmp/a1 1"
var2=`echo -e "$var0\n$var1"`
现在,如果我检查自己并打印此列表,一切似乎都正常:
echo "$var2"
#returns:
#/tmp/a0 1
#/tmp/a1 1
但是如果我尝试获取总大小,它会以某种方式误解“\n”符号
du "$var2"
#returns:
#du: cannot access ‘/tmp/a0 1\n/tmp/a1 1’: No such file or directory
如何使 du 进程“\n”作为行分隔符?或者也许我必须以不同的方式创建列表?
答案1
答案2
我找到的解决方案是var2
在循环中逐行分割while
:
#!/bin/bash
var0="/tmp/a0 1"
var1="/tmp/a1 1"
var2="$(echo -e "$var0\n$var1")"
totalsize=0; #this will make script return 0 if var2 somehow contains empty lines only
while read "opened_file" #for each file in list do
do
if [ ! -z "$opened_file" ]; then #if variable is not empty
tmp1="$(du -b "$opened_file" | cut -d" " -f1)" #get size of current file and strip unnecessary fields
totalsize=$(($totalsize + $tmp1))
fi
done <<< "$(echo -e "$var2")"
echo "$totalsize"