Bash Handling Complex Commands as Strings: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
=Internal=
=Internal=
* [[Bash#bash_Script_Library|bash]]
* [[Bash#bash_Script_Library|bash]]
* [[curl]]
* [[Curl#Executing_curl_from_Scripts|curl]]


=Overview=
=Overview=
Line 16: Line 16:
mode=POST
mode=POST
post_body='{"color": "green", "size": 10}'
post_body='{"color": "green", "size": 10}'
url=https://example.com
url=https://example.com/something
query_parameters="?a=1\&b=2\&c=3"


command='curl -s -H "X-SOME-HEADER: '${some_header_value}'" -H "X-SOME-SECURITY-SENSITIVE-HEADER: '${some_security_sensitive_header_value}'" -H "Content-Type: application/json" -X '${mode}
command='curl -s -H "X-SOME-HEADER: '${some_header_value}'" -H "X-SOME-SECURITY-SENSITIVE-HEADER: '${some_security_sensitive_header_value}'" -H "Content-Type: application/json" -X '${mode}
Line 22: Line 23:
   command="${command} -d '${post_body}'"
   command="${command} -d '${post_body}'"
fi
fi
command="${command} ${url}"
command="${command} ${url}${query_parameters}"


command_with_masked_token=$(echo "${command}" | sed -e 's/X-SOME-SECURITY-SENSITIVE-HEADER: .*-H/X-SOME-SECURITY-SENSITIVE-HEADER: ***" -H/')
command_with_masked_token=$(echo "${command}" | sed -e 's/X-SOME-SECURITY-SENSITIVE-HEADER: .*-H/X-SOME-SECURITY-SENSITIVE-HEADER: ***" -H/')
echo "[debug]: ${command_with_masked_token}"
echo "[debug]: ${command_with_masked_token//\\/}"
output=$(sh -c "${command}") || { echo "command failed" 1>&2 2>/dev/stderr; }
output=$(sh -c "${command}") || { echo "command failed" 1>&2 2>/dev/stderr; }
echo "${output}"
echo "${output}"
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 19:44, 16 October 2023

Internal

Overview

The essence of the example is building the command as a string while properly handling combinations of single and double quotes, then executing the command with:

$(sh -c "${command}")
echo "${output}"

Example

some_header_value='blue'
some_security_sensitive_header_value='red'
mode=POST
post_body='{"color": "green", "size": 10}'
url=https://example.com/something
query_parameters="?a=1\&b=2\&c=3"

command='curl -s -H "X-SOME-HEADER: '${some_header_value}'" -H "X-SOME-SECURITY-SENSITIVE-HEADER: '${some_security_sensitive_header_value}'" -H "Content-Type: application/json" -X '${mode}
if [[ ${mode} == 'POST' ]]; then
  command="${command} -d '${post_body}'"
fi
command="${command} ${url}${query_parameters}"

command_with_masked_token=$(echo "${command}" | sed -e 's/X-SOME-SECURITY-SENSITIVE-HEADER: .*-H/X-SOME-SECURITY-SENSITIVE-HEADER: ***" -H/')
echo "[debug]: ${command_with_masked_token//\\/}"
output=$(sh -c "${command}") || { echo "command failed" 1>&2 2>/dev/stderr; }
echo "${output}"