Bash - 加入数组时连接反斜杠

时间:2014-08-04 17:21:59

标签: arrays bash gruntjs

我一直试图找出一个bash脚本来确定服务器目录路径,例如D:\ xampp \ htdocs,以及项目文件夹名称,例如" my_project",同时Grunt正在运行我的postinstall脚本。到目前为止,我可以获取项目文件夹名称,并且我可以获得包含我的系统上的服务器根路径的其余索引的数组,但我似乎无法使用转义反斜杠加入数组。这可能不是最好的解决方案(绝对不是最优雅的),所以如果你有任何提示或建议,我可以修改。

# Determine project folder name and server root directory path
bashFilePath=$0                           # get path to post_install.sh
IFS='\' bashFilePathArray=($bashFilePath) # split path on \
len=${#bashFilePathArray[@]}              # get array length

# Name of project folder in server root directory
projName=${bashFilePathArray[len-3]}      # returns my_project

ndx=0
serverPath=""
while [ $ndx -le `expr $len - 4` ]
do
    serverPath+="${bashFilePathArray[$ndx]}\\" # tried in and out of double quotes, also in separate concat below
    (( ndx++ ))
done

echo $serverPath # returns D: xampp htdocs, works if you sub out \\ for anything else, such as / will produce D:/xampp/htdocs, just not \\

1 个答案:

答案 0 :(得分:2)

您只能使用IFS为命令调用而不是变量赋值加前缀,因此您的行

 IFS='\' bashFilePathArray=($bashFilePath)

只是一对作业; $bashFilePath的扩展不受IFS的分配的影响。相反,请使用read内置。

IFS='\' read -ra bashFilePathArray <<< "$bashFilePath"

稍后,您可以使用子shell轻松地将数组的前几个元素连接成一个字符串。

serverPath=$(IFS='\'; echo "${bashFilePathArray[*]:0:len-3}")

分号是必需的,因为echo的参数在echo实际运行之前展开,这意味着IFS需要“全局”修改,而不仅仅是echo 1}}命令。此外,需要[*]来代替更常见的[@],因为在这里我们明确使用了这样一个属性,即这种数组扩展的元素将产生一个单词而不是一个单词序列

相关问题