如何使用bash使用if语句捕获两个变量的返回值?

时间:2011-04-21 15:22:38

标签: macos bash

我的任务是在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

2 个答案:

答案 0 :(得分:2)

  1. Do not parse the output of ls除非您绝对必须这样做。上面的代码存在主要问题,文件夹名称中有空格。

  2. 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
相关问题