tags:

views:

626

answers:

3

hi

i want write code to add in line for ex open inittab file and add

c2:1235:respawn:/sbin/agetty 38400 tty2 linux
c3:1235:respawn:/sbin/agetty 38400 tty3 linux
c4:1235:respawn:/sbin/agetty 38400 tty4 linux
c5:1235:respawn:/sbin/agetty 38400 tty5 linux
c6:12345:respawn:/sbin/agetty 38400 tty6 linux
<<~~~ i want add code here 

# Local serial lines:
#s1:12345:respawn:/sbin/agetty -L ttyS0 9600 vt100
#s2:12345:respawn:/sbin/agetty -L ttyS1 9600 vt100

is there any way to do this in bash ?

+1  A: 

Modify your inittab, then "init -q" to reload it. If your question is about file editing in bash, you can read a file and rewrite it in a loop like this :

for i in `cat thefile`
do
   echo $i >> someOtherFile
   if [ "some condition" == "some condition" ];
       then
       # do something else
   fi
done

This will read "thefile" line by line and write to "someOtherFile" while allowing you to insert whatever test to add lines in the flow.

wazoox
note that cat will "break the lines" when there are white spaces. better to use a while read loop, or set IFS to \n.
ghostdog74
Yes, that's right. Apparently the OP asked for the very basics of shell programming, so that's what I aimed to :)
wazoox
A: 

one way

# awk '/^# Local serial lines/{ print "I wanna add code here\n"}1' /etc/inittab > temp
# mv temp /etc/inittab

then do init -q as wazoox says.

the other way: edit your inittab manually if its one time only.

ghostdog74
+1  A: 

Here is an alternative to wazoox script using an embedded awk snippet (I have added the init -q from wazoox)

#!/bin/bash

my_file=/etc/inittab
my_pattern="c6:12345:respawn:.* 38400 tty6 linux"

awk -f - ${my_file}<<__END__
{ print }
/${my_pattern}/ { 
    print "any code you want to add" 
}
__END__

init -q

Just check the pattern you want to detect and use "man awk" for the use of print. If you have a big code chunk to add you can use $(cat ${my_code_file}) in the awk snippet.

neuro