[英]Passing a path to BASH script with a variable
I've written a little script that uses the hdiutil
in OSX but I'm having an issue when passing a path to the output variable where the path contains spaces. 我已经写了一个小脚本,在OSX中使用
hdiutil
,但是在将路径传递到包含空格的输出变量时遇到了问题。 The path is generated simply by the user dragging the path folder onto the terminal window and then reading that to a variable. 只需通过用户将路径文件夹拖动到终端窗口,然后将其读取到变量中即可生成路径。 Basically I have for the path:
基本上我有路径:
echo "Drag Destination Folder to Window or Leave Blank to Create on Desktop:"
read createDest
createDest=$(echo "$createDest" | sed 's/ /\\ /g')
I then prompt for the desired name with 然后,我提示输入所需的名称
echo "Enter Name for Image (also used for Volume):"
read varName
varName=$(sed -e 's/[^A-Za-z0-9._-]/_/g' <<< $varName) #remove illegal chars
Combine them with path=$(echo ${createDest}/${varName})
将它们与
path=$(echo ${createDest}/${varName})
And finally generate the file with 最后用生成文件
Echo -n $varPass | hdiutil create -encryption -stdinpass -type SPARSEBUNDLE -size ${varSize}G -fs HFS+J -volname $varName $path
This all works fine as long as there are no spaces in the path but as soon as there are I get an error from hdiutil
stating: 只要路径中没有空格,所有这些都可以正常工作,但是一旦我从
hdiutil
收到一条错误hdiutil
说明:
hdiutil: create: Only one image can be created at a time.
If I type the pass in manually its fine so I'm a bit confused as to where my formatting has gone wrong. 如果我手动输入密码的话,我对格式哪里出了问题有些困惑。
Any help would be very much appreciated. 任何帮助将不胜感激。
Cheers 干杯
Chris 克里斯
在所有位置引用所有变量:
echo -n "$varPass" | hdiutil create -encryption -stdinpass -type SPARSEBUNDLE -size "${varSize}G" -fs HFS+J -volname "$varName" "$path"
All you need to do is quote the parameter expansions; 您需要做的就是引用参数扩展名。 that is sufficient to protect the whitespace.
这足以保护空白。 Adding backslashes manually simply creates a value that does not represent an existing path.
手动添加反斜杠仅会创建一个不代表现有路径的值。
echo "Drag Destination Folder to Window or Leave Blank to Create on Desktop:"
read createDest
echo "Enter Name for Image (also used for Volume):"
read varName
varName=${varName//[^[:alnum:]._-]/_} # more efficient than running sed
printf '%s' "$varPass" | hdiutil create -encryption -stdinpass -type SPARSEBUNDLE -size "${varSize}G" -fs HFS+J -volname "$varName" "$path"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.