是否有任何方法可以迭代 bash 脚本中传递的参数?我的问题的这个答案向我展示了如何使用每个参数,但我想迭代它们,因为参数的数量是可变的。
我试过类似的东西:
for i in {1..10}
do
if [[ -f "$($i)" ]]
then
echo "$($i) is a file"
elif [[ -d "$($i)" ]]
then
echo "$($i) is a directory"
else
echo "$($i) is not a file or directory"
fi
done
Run Code Online (Sandbox Code Playgroud)
但它给了我错误。我也尝试使用但没有成功,$$i而不是$($i)......
您应该使用$@来引用所有参数:
for arg in "$@"
do
if [[ -f "$arg" ]]
then
echo "$arg is a file"
elif [[ -d "$arg" ]]
then
echo "$arg is a directory"
else
echo "$arg is not a file or directory"
fi
done
Run Code Online (Sandbox Code Playgroud)
另见:http : //www.tldp.org/LDP/abs/html/internalvariables.html#ARGLIST