如何使用for..内部的位置参数循环浏览目录中的所有内容..循环中



我试图显示用户给我的任何目录的内容,并试图使用for。。。循环中。与参数$1相等的名为dir的变量不会接受我的for循环中的变量。我得到一个错误,说$dir不是一个有效的标识符。我只是想知道我应该放什么,这样它就可以遍历用户目录,看看它们是文件还是目录。我希望我说的有道理。

#!/bin/bash
dir=$1
for $dir in *
do
if [[ -d "$dir" ]]; then
echo "$dir is a directory"
elif [[ -f "$dir" ]]; then
echo "$dir is a file"
fi
done

这里不迭代$dir repository的内容。

在这里使用for循环

进行

# here you build a correct path from where the script is run 
dir="${PWD}/$1"
# here you can test if the rep passed in args exist ifnot, exit 
[[ ! -e "$dir" ]] && exit 0 
for cursor in $dir/*; do 
if [[ -d "$cursor" ]]; then
echo "$cursor is a directory"
elif [[ -f "$cursor" ]]; then
echo "$cursor is a file"
fi 
done 

到目前为止,您已经接近了。如果用户没有提供当前目录,那么最好使用当前目录。

在使用glob模式之前,您应该首先检查用户提供的是否是目录。还要记住,有些文件既不是目录也不是常规文件。

#!/bin/bash
if [[ $# -lt 1 ]]; then
target=./
else
target=$1
fi
[[ -e "$target" ]] || { echo "$1: Does not exist" >&2; exit 1; }
[[ -d "$target" ]] || { echo "$1: Not a directory" >&2; exit 1; }
[[ -r "$target" ]] || { echo "$1: No read permission" >&2; exit 1; }
if [[ $# -lt 1 ]]; then
target=
else
# User may or may not give a trailing slash, so guarantee one.
target=${target%/}/
fi
for i in "$target"*; do
if [[ -d "$i" ]]; then
echo "$i is a directory"
elif [[ -f "$i" ]]; then
echo "$i is a file"
else
echo "$i is not a directory or regular file"
fi
done

最新更新