Algorithms, Blockchain and Cloud

BASH Function to Escape Parameters Argument


We can use the following BASH function escape to escape the parameter strings and put them one by one. For example:

#!/bin/bash

function escape () {
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
}

escape $*

Using the prinftf with sed to escape the strings:

Example:

$ ./escape 1234 a 4 "5 a"
'1234' \
'a' \
'4' \
'5' \
'a' \
$ ./escape 1234 a 4 ''
'1234' \
'a' \
'4' \
$ ./escape 1234 a 4 ' '
'1234' \
'a' \
'4' \
$ ./escape 1234 a 4 'ss1234'
'1234' \
'a' \
'4' \
'ss1234' \
$ ./escape 1234 a 4 'ss1234' "'"
'1234' \
'a' \
'4' \
'ss1234' \
''\''' \
$ ./escape 1234 a 4 'ss1234' "''"
'1234' \
'a' \
'4' \
'ss1234' \
''\'''\''' \
$ ./escape 1234 a 4 'ss1234' "<>"
'1234' \
'a' \
'4' \
'ss1234' \
'<>' \
$ ./escape 1234 a 4 'ss1234' "<>"
'1234' \
'a' \
'4' \
'ss1234' \
'<>' \

BASH Programming/Shell

–EOF (The Ultimate Computing & Technology Blog) —

219 words
Last Post: Teaching Kids Programming - Count Square Sum (Pythagorean) Triples
Next Post: Teaching Kids Programming - Brick Layout (Unlimited Knapsack) via Top Down Dynamic Programming Algorithm

The Permanent URL is: BASH Function to Escape Parameters Argument (AMP Version)

Exit mobile version