I have the following function I want to call:
function print_something {
echo "test\
something\
yep"
}
when called it prints:
'test something yep'
I would like it to print:
'testsomethingyep'
I can get this to print if I do:
function print_something {
echo "test\
something\
yep"
}
but I don't think that looks great..
(Root problem is a curl command not an echo)
CodePudding user response:
Consider assembling your pieces an array, and then combining them into a string later. Array definition syntax is far more forgiving -- not requiring backslashes at all, and also allowing comments on each line and between lines.
#!/usr/bin/env bash
# ^^^^- arrays and printf -v require bash, not sh
pieces=(
test # this also lets you use comments
something # and you don't need any backslashes at all!
# one can also have a full-line comment midway through your array
"space here" # plus if you want to add a literal space you can do it
)
printf -v oneword '%s' "${pieces[@]}"
echo "$oneword"
...properly emits:
testsomethingspace here
CodePudding user response:
Here are three ideas:
#!/bin/bash
print_something() {
tr -d \\n <<- EOF
test
something
yep
EOF
echo
}
print_something2() {
echo "test"$(:
)"something"$(:
)"yep"
}
print_something3() {
tr -d \\t <<- EOF
test\
something\
yep
EOF
}
print_something
print_something2
print_something3
The first uses a <<-
style heredoc to remove all of the leading indentation (that indentation must be hard-tabs for this to work, and coding styles that mandate the use of spaces for indentation render this solution unusable (this is one reason coding styles that mandate the use of spaces in shell scripts are IMO utterly useless)) and the extra tr
to remove the newlines. (The additional echo is then needed to add the trailing newline.). The second uses the $(:)
command substitution to discard all the intervening whitespace. The 3rd manually deletes all the hard tabs.