简体   繁体   English

列出文件夹,但如果文件夹与 Bash 中的列表匹配,则排除

[英]Listing folders but exclude if folder matched from listing in Bash

I am playing around with Bash for the first time.我第一次玩 Bash。

This script will list all folders, however I want to modify it to not list a certain folder if possible.此脚本将列出所有文件夹,但是我想修改它以尽可能不列出某个文件夹。

Working:工作:

_list_banners () {
  for f in * ; do [ -d "$f" ] && echo ${_handle_banner_type}${_handle_message} $f ; done
}

This works and lists the folders, but I want to exclude for example folder MASTER from the list.这有效并列出了文件夹,但我想从列表中排除例如文件夹MASTER

Attempted:尝试:

_list_banners () {
  for f in * ;
    if [ $f != "MASTER" ]; then
      do [ -d "$f" ] && echo ${_handle_banner_type}${_handle_message} $f
    fi
  ; done
}

But when I run it, I get the following error instead of my file list:但是当我运行它时,我收到以下错误而不是我的文件列表:

$ bash myscript
myscript: line 3: syntax error near unexpected token `if'
myscript: line 3: `    if [ $f != "MASTER" ]; then'

do is part of the for loop and shouldn't be moved inside the if block: do是 for 循环的一部分,不应在if块内移动:

_list_banners () {
  for f in * ;
  do 
    if [ "$f" != "MASTER" ]; then
      [ -d "$f" ] && echo "${_handle_banner_type}${_handle_message} $f"
    fi
  done
}

You could move both the directory check and the exclusion into your glob (requires shopt -s extglob , and shopt -s nullglob would be a good idea to avoid unexpected behaviour when nothing matches):您可以将目录检查和排除移动到您的 glob 中(需要shopt -s extglobshopt -s nullglob是一个好主意,以避免在没有任何匹配时出现意外行为):

shopt -s extglob
shopt -s nullglob

_list_banners () {
    for f in !(MASTER)/; do 
        echo "${_handle_banner_type}${_handle_message} $f"
    done
}

!(MASTER) is a glob that excludes MASTER , and appending / only returns directories. !(MASTER)是一个排除MASTER的 glob,并且附加/仅返回目录。

If you want just the directory name without the trailing slash, you can use ${f%/} instead of just $f on the echo line.如果您只想要目录名而没有尾部斜杠,您可以在echo行上使用${f%/}而不是$f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM