简体   繁体   中英

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. 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})

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: 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM