Bash 目录上的 For 循环

发布于 2024-09-28 13:46:30 字数 406 浏览 2 评论 0原文

快速背景:

$ ls src
file1  file2  dir1  dir2  dir3

脚本:

#!/bin/bash

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

输出:

src/dir1
src/dir2
src/dir3

但是,我希望它读取:

dir1
dir2
dir3

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自演自醉 2024-10-05 13:46:30

echo 行执行此操作:

 echo $(basename "$i")

Do this instead for the echo line:

 echo $(basename "$i")
和我恋爱吧 2024-10-05 13:46:30

无需分叉外部进程:

echo "${i##*/}"

它使用“删除最长匹配前缀”参数扩展
*/ 是模式,因此它将删除从字符串开头到最后一个斜杠的所有内容。如果$i 的值中没有斜线,则与"$i" 相同。

这个特定的参数扩展在 POSIX 中指定,并且是原始 Bourne shell 的遗产。所有类似 Bourne 的 shell(shashdashkshbash 均支持它zsh 等)。许多功能丰富的 shell(例如 kshbashzsh)都有其他扩展,可以在不涉及外部进程的情况下处理更多内容。

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".

This particular parameter expansion is specified in POSIX and 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.

俯瞰星空 2024-10-05 13:46:30

如果您在脚本开始时执行cd,则在脚本退出时应该将其恢复。

#!/bin/bash

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

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

#!/bin/bash

cd src
for i in * ; do
  if [ -d "$i" ]; then
    echo "$i"
  fi
done
你丑哭了我 2024-10-05 13:46:30

使用 basename 作为:

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

Use basename as:

if [ -d "$i" ]; then
    basename "$i"
fi
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文