使用"ls"安全吗?在bash中进行循环 [英] is it safe to use "ls" in for loop in bash
本文介绍了使用"ls"安全吗?在bash中进行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用它来遍历/home目录中的文件夹
I am using this to loop through folders in /home directory
for FOLDERNAME in `\ls -1 /home/`
我想知道这是安全的
推荐答案
如果要在/home
中使用所有子目录,请使用
If you want all subdirectories in /home
, use
( # run in subshell so "shopt -s dotglob" doesn't affect rest of script
shopt -s dotglob
for DIR in /home/*/; do
DIRNAME=`basename "$DIR"`
# do whatever with "$DIR" or "$DIRNAME"
echo -n "$DIRNAME"|od -t cz
done
)
注意尾部斜杠和引用的变量.
Note the trailing slash and the quoted variables.
带有目录和文件
mkdir /home/..abc
mkdir /home/.abc
mkdir /home/$'a\nc'
mkdir /home/'a?c'
mkdir /home/abc
mkdir /home/'foo bar'
touch /home/test
这给了我输出
0000000 . . a b c >..abc<
0000005
0000000 . a b c >.abc<
0000004
0000000 a \n c >a.c<
0000003
0000000 a ? c >a?c<
0000003
0000000 a b c >abc<
0000003
0000000 f o o b a r >foo bar<
0000007
其中
ls -1 -F -b -A /home
将输出提供给我
..abc/
.abc/
a\nc/
a?c/
abc/
foo bar/
test
(test
是文件)
这篇关于使用"ls"安全吗?在bash中进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文