Bash 目录上的 For 循环
快速背景:
$ 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对
echo
行执行此操作:Do this instead for the
echo
line:无需分叉外部进程:
它使用“删除最长匹配前缀”参数扩展。
*/
是模式,因此它将删除从字符串开头到最后一个斜杠的所有内容。如果$i
的值中没有斜线,则与"$i"
相同。这个特定的参数扩展在 POSIX 中指定,并且是原始 Bourne shell 的遗产。所有类似 Bourne 的 shell(sh、ash、dash、ksh、bash 均支持它、zsh 等)。许多功能丰富的 shell(例如 ksh、bash 和 zsh)都有其他扩展,可以在不涉及外部进程的情况下处理更多内容。
No need for forking an external process:
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.
如果您在脚本开始时执行
cd
,则在脚本退出时应该将其恢复。If you do a
cd
at the start of the script, it should be reverted when the script exits.使用
basename
作为:Use
basename
as: