我需要一个脚本来获取Mac上/ Volumes目录中的所有目录并将它们存储在一个数组中。 我遇到的问题是,在目录名中有一个空格是很常见的,这真的让人感到困惑。 这是我到目前为止所得到的:
LOCATION="/Volumes" COUNTER=0 cd $LOCATION OIFS=$IFS IFS=$'\n' for folder in *; do [ -d "$folder" ] || continue (( DRIVES[$COUNTER] = ${folder} )) (( COUNTER = COUNTER + 1 )) done IFS=$OIFS这是我得到的错误:
./getDrives.sh: line 17: DRIVES[0] = Macintosh HD : syntax error in expression (error token is "HD ")I need a script that will get all of the directories within the /Volumes directory on a Mac and store them in an array. The problem that I am running into is that it is very common for there to be a space in a directory name, and that really messes things up. Here is what I've got so far:
LOCATION="/Volumes" COUNTER=0 cd $LOCATION OIFS=$IFS IFS=$'\n' for folder in *; do [ -d "$folder" ] || continue (( DRIVES[$COUNTER] = ${folder} )) (( COUNTER = COUNTER + 1 )) done IFS=$OIFSHere is the error that I am getting:
./getDrives.sh: line 17: DRIVES[0] = Macintosh HD : syntax error in expression (error token is "HD ")最满意答案
我想最简单的只是:
array=( /Volumes/*/ )笔记:
将此与nullglob或failglob集一起使用 如果你也想要隐藏目录(但不是.也不.. ),请设置dotglob如果你想要所有的目录和子目录(递归),设置globstar并使用
array=( /Volumes/**/ )代替。
当我说set nullglob或failglob或dotglob或globstar我指的是shell选项,可以设置,例如:
shopt -s nullglob并且未设置,例如:
shopt -u nullglob有关这些内容的更多信息,请参阅Bash参考手册的Shopt Builtin部分 。
要回答你的评论:你只想要目录的基名,而不是完整的路径? 简单,只是做
cd /Volumes array=( */ )就这样。 事实上,我建议你用一条效率更高的代码替换6行低效代码。
更一般地说,如果你不想进入/Volumes ,你可以很容易地摆脱领先/Volumes/ like
array=( /Volumes/*/ ) array=( "${array[@]/#\/Volumes\//}" )或者,更好的是,将前导/Volumes/置于变量中并继续:
location="/Volumes/" array=( "$location"* ) array=( "${array[@]/#"$location"/}" )I guess the simplest is just:
array=( /Volumes/*/ )Notes:
use this with nullglob or failglob set if you also want hidden directories (but not . nor ..), set dotglobif you want all the directories and subdirectories (recursively), set globstar and use
array=( /Volumes/**/ )instead.
When I say set nullglob or failglob or dotglob or globstar I mean the shell options, that can be set with, e.g.:
shopt -s nullgloband unset with, e.g.:
shopt -u nullglobMore about these in The Shopt Builtin section of the Bash Reference Manual.
To answer your comment: you only want the basename of the directories, not the full path? easy, just do
cd /Volumes array=( */ )That's all. In fact, I'm suggesting you replace 6 lines of inefficient code with just one, much more efficient, line.
More generally, if you don't want to cd into /Volumes, you can easily get rid of the leading /Volumes/ like so
array=( /Volumes/*/ ) array=( "${array[@]/#\/Volumes\//}" )Or, even better, put the leading /Volumes/ in a variable and proceed as:
location="/Volumes/" array=( "$location"* ) array=( "${array[@]/#"$location"/}" )更多推荐
发布评论