Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indenting code when redirecting text

Tags:

bash

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.

like image 699
user117974 Avatar asked Mar 21 '23 19:03

user117974


2 Answers

Use

cat<<-EOF
   text123
EOF
like image 147
user2719058 Avatar answered Apr 05 '23 21:04

user2719058


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.

like image 41
Jonathan Leffler Avatar answered Apr 05 '23 22:04

Jonathan Leffler