Skip to content

Instantly share code, notes, and snippets.

@Lohann
Last active March 20, 2026 02:06
Show Gist options
  • Select an option

  • Save Lohann/348bf80be6d4c719b3025c98a8b2e1ff to your computer and use it in GitHub Desktop.

Select an option

Save Lohann/348bf80be6d4c719b3025c98a8b2e1ff to your computer and use it in GitHub Desktop.
#!/bin/sh
# single quote arguments using only pure shell, this
# script doesn't require any external programn such as `sed`.
quote ()
{
test $# -gt 0 || return 0
while test $# -gt 1
do
quote "$1" || return $?
# use first character of IFS as separator.
printf '%c' "$IFS"
shift
done
set x "[']" "$IFS" "$1" && shift || return $?
case $3 in
$1)
# string is single quote character
printf '%s' "\\'"
return 0
;;
*$1)
# string ends in single quotes
IFS="'"; set x "$2" $3 '' || { IFS=$2; return 1; }
;;
*$1*)
# string has single quotes
IFS="'"; set x "$2" $3 || { IFS=$2; return 1; }
;;
*)
# string doesn't have single quotes
printf '%s' "'$3'"
return 0
;;
esac
IFS=$2
shift && shift || return $?
test "x$1" = x || printf '%s' "'$1'"
while test $# -gt 1
do
shift || return $?
if test "x$1" = x
then printf '%s' "\\'"
else printf '%s' "\\''$1'"
fi
done
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment