I would like to know if there is a solution to this issue.
In my shell script I have some code to redirect some text to a file:
if [ condition ]; then
cat > /outputfile <<EOF
text123
text345
text456
EOF
fi
The problem is I want textxxx indented in my code, however if I do this then the redirected text would have spaces in it.
Is there a way I could indent the code nicely and have the output file without spaces.
Use
cat<<-EOF
text123
EOF
The standard answer is to use leading tabs (and they must be tabs, not blanks) and the -
before the 'word':
cat <<-'EOF'
Tab-indented text
Blank-indented text
EOF
Which (if you have one or more actual tabs before 'Tab-indented') will output:
Tab-indented text
Blank-indented text
If that's too inconvenient, then one alternative is to use sed
instead of cat
:
sed 's/^[ ]*//' <<EOF
Randomly
Indented
Text
EOF
which will output:
Randomly
Indented
Text
(Again, you have to be sure that there are tabs in the right places; here, that means in the regular expression in the sed
command. Or you could use sed 's/^[[:space:]]*//'
if you prefer.)
Note that the use of 'EOF'
vs EOF
affects how the body of a here document is (or is not) interpreted. Compare:
cat <<-EOF
$(rm -fr *) # Do not try this at home! (Or at work.)
$HOME
EOF
and
cat <<-'EOF'
$(rm -fr *)
$HOME
EOF
The first will have the shell recognize the $(...)
notation and execute the command and substitute the output (nothing) into the here document. Sorry about the work you've been doing over the last year or two! Hope you've got good backups. The second will treat the content of the script verbatim apart from removing leading tabs - which is safer, though any notation like $(rm -fr *)
is not very safe! The variable $HOME
will be expanded in the first version; it will be left unchanged in the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With