Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line breaking in bash script

Tags:

bash

newline

In my company style guide it says that bash scripts cannot be longer than 80 lines. So I have this gigantic sed substitution over twice as long. How can I break it into more lines so that it still works? I have

sed -i s/AAAAA...AAA/BBBBB...BBB/g

And I want something like

sed -i s/AAAAA...AAA/
BBBBB...BBB/g

still having the same effect.

like image 984
siemanko Avatar asked Aug 07 '12 01:08

siemanko


People also ask

How do I continue a new line in bash?

Linux Files, Users, and Shell Customization with Bash If you want to break up a command so that it fits on more than one line, use a backslash (\) as the last character on the line. Bash will print the continuation prompt, usually a >, to indicate that this is a continuation of the previous line.

What is a line break in Linux?

In Windows and DOS, the line break code is two characters: a carriage return followed by a line feed (CR/LF). In the Unix/Linux/Mac world, the code is just the line feed character (LF).

Is there break in bash?

In Bash scripting, a break statement helps provide control inside loop statements. Instead of waiting until the end condition, a break statement helps exit from a loop before the end condition happens.

How do you go down a line in Linux?

Moving to Start or End of LinePress ^ to move the cursor to the start of the current line. Press $ to move the cursor to the end of the current line.


2 Answers

Possible ways to clean up

1) Put your sed script into a file

sed -f script [file ...]

2) Use Regex shorthand

sed 's!A\{30,\}!BBBBB...BBBB!g'

3) Use Bash variables to help break it up a bit

regex="AAAA.AAAAAA"
replace="BBBB...BBBBBBB"
sed "s/${regex}/${replace}/g"

What not to do

1) Escape the newline to break it up into multiple lines.

You will end up with a newline in your sed script that you don't want.

sed 's/THIS IS WRONG /\
AND WILL BREAK YOUR SCRIPT/g'
like image 137
Swiss Avatar answered Nov 15 '22 05:11

Swiss


Use the shell continuation character, which is normally \.

[~]$ foo \
> and \
> bar

Space is not required:

[~]$ foo\
> and\
> bar\
> zoo\
> no space\
> whee!\
like image 23
Burhan Khalid Avatar answered Nov 15 '22 05:11

Burhan Khalid