我的任务是在Mac上的/ Users中列出用户的文件夹。我必须允许dupe文件夹(大型企业650 mac客户端)或桌面分析师备份文件夹并附加内容。我的$fourFour
变量选中了它。但是,我必须将其标记为记录。
这是我在下面的地方。变量$fourFour
可能会返回一个或多个文件夹,我需要获取if语句来相应地回显它。
folders=$(ls -d */ | grep $fourFour | awk '{print $(NF)}' | sed 's/\///')
echo folders is $folders
if [[ "$folders" == "" ]]; then
echo no items
else
echo one or more items
fi
答案 0 :(得分:2)
Do not parse the output of ls
除非您绝对必须这样做。上面的代码存在主要问题,文件夹名称中有空格。
Bash arrays可以成为你的朋友:
#!/bin/bash
shopt -s nullglob
folders=(*$fourFour*/)
# Remove the trailing slashes
folders=("${folders[@]%/}")
if [[ "${#folders[@]}" -gt 0 ]]; then
echo "Folders:" "${folders[@]}"
else
echo "No folders"
fi
答案 1 :(得分:1)
您无需调用这么多工具来查找文件夹。只需使用shell(bash)
#!/bin/bash
shopt -s nullglob
for dir in *$fourFour*/ # putting a slash "/" ensures you get directory entries
do
echo "Do something with $dir"
# if you want to check if its empty folder
v=$(echo "$dir"/*)
case "${#v}" in
0) echo "No files in $dir";;
*) echo "Files in $dir";;
esac
done
如果您只是想检查是否有任何符合您的模式的文件夹
v=$(echo "$four"/)
case "${#v}" in
0) echo "0 item";;
*) echo "1 or more item";;
esac