目录上的 Bash For 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4011668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:48:36  来源:igfitidea点击:

Bash For-Loop on Directories

bashloopsshelldirectory

提问by BassKozz

Quick Background:

快速背景:

$ ls src
file1  file2  dir1  dir2  dir3

Script:

脚本:

#!/bin/bash

for i in src/* ; do
  if [ -d "$i" ]; then
    echo "$i"
  fi
done

Output:

输出:

src/dir1
src/dir2
src/dir3

However, I want it to read:

但是,我希望它阅读:

dir1
dir2
dir3

Now I realize I could sed/awk the output to remove "src/" however I am curious to know if there is a better way of going about this. Perhaps using a find + while-loop instead.

现在我意识到我可以 sed/awk 输出来删除“src/”但是我很想知道是否有更好的方法来解决这个问题。也许使用 find + while-loop 代替。

采纳答案by Gonzalo

Do this instead for the echoline:

为该echo行执行此操作:

 echo $(basename "$i")

回答by Chris Johnsen

No need for forking an external process:

无需分叉外部进程:

echo "${i##*/}"

It uses the “remove the longest matching prefix” parameter expansion. The */is the pattern, so it will delete everything from the beginning of the string up to and including the last slash. If there is no slash in the value of $i, then it is the same as "$i".

它使用“删除最长匹配前缀”参数扩展。的*/是模式,所以它会从字符串截至及包括最后的斜线的开始删除所有内容。如果 的值中没有斜线$i,则与 相同"$i"

This particular parameter expansion is specified in POSIXand is part of the legacy of the original Bourne shell. It is supported in all Bourne-like shells (sh, ash, dash, ksh, bash, zsh, etc.). Many of the feature-rich shells (e.g. ksh, bash, and zsh) have other expansions that can handle even more without involving external processes.

这个特殊的参数扩展是在 POSIX 中指定的,是原始 Bourne shell 的一部分。所有类似 Bourne 的 shell(shashdashkshbashzsh等)都支持它。许多功能丰富的外壳程序(例如kshbashzsh)具有其他扩展,可以在不涉及外部进程的情况下处理更多。

回答by Mark Ransom

If you do a cdat the start of the script, it should be reverted when the script exits.

如果您cd在脚本开始时执行 a ,则应在脚本退出时将其还原。

#!/bin/bash

cd src
for i in * ; do
  if [ -d "$i" ]; then
    echo "$i"
  fi
done

回答by codaddict

Use basenameas:

使用basename如:

if [ -d "$i" ]; then
    basename "$i"
fi