Brian Langhoff
Brian Langhoff

Reputation: 151

Escaping double quotes in a variable in a shell script

hopefully a simple question and the last piece in my puzzle... :-) I have a shell script running in terminal under os x. It contains among other things:

name=$(basename "$file")
printf "%s" "\"$name\";"

... which is fine ... but lets say that the file name contains a double quote - IMA"G09%'27.jpg - then the output would be:

"IMA"G09%'27.jpg;"

... and that would "break" my line intended for putting into a db later (the double quote). So I need to escape it so I get the output:

"IMA\"G09%'27.jpg;"

... but I couldn't figure out how ... anyone? :-)

EDIT - RESULT: With the help of anubhava this is what I use (to get file info incl. type/creator):

#!/bin/bash

find . -type f -name '*' -print0 | while IFS= read -r -d '' file
do
    name=$(basename "$file")
    path=$(dirname "$file")
    # full_path=$(readlink -f "$file") # This only works on Linux
    full_path=$(echo "$PWD/${file#./}")
    extension=${name##*.}
    size_human_readable=$(ls -lh "$file" | awk -F' ' '{print $5}')
    size_in_bytes=$(stat -f "%z" "$file")
    creation_date=$(stat -f "%SB" "$file")
    last_access=$(stat -f "%Sa" "$file")
    last_modification=$(stat -f "%Sm" "$file")
    last_change=$(stat -f "%Sc" "$file")
    creator=$(mdls -name kMDItemFSCreatorCode "$file")


    printf "\"%q\";" "$name"
    printf "%s" "\"$full_path\";"
    printf "%s" "\"$extension\";"
    printf "\"$size_human_readable\";"
    printf "\"$size_in_bytes\";"
    printf "\"$last_modification\";"
    printf "%s" "\"$creator\""
    printf "\n"
done

Upvotes: 3

Views: 5693

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125708

Here's another approach, using sed to control the escaping:

printquoted() {
    printf '"%s";' "$(LC_ALL=C sed 's/["]/\\&/g' <<<"$1")"
}

printquoted "$name"
printquoted "$full_path"
printquoted "$extension"
...etc

If it turns out there are other things you need to escape besides double-quotes (like, say, backslashes themselves), you can add them to the sed [] expression (e.g. ["\] would escape double-quotes and backslashes).

Note that this approach will fail horribly if the string contains any newlines (which is legal in filenames).

Upvotes: 0

anubhava
anubhava

Reputation: 784938

Using printf with %q:

name='file"naeme.txt'

printf "\"%q;\"" "$name"
"file\"naeme.txt;"

Upvotes: 3

Related Questions