Flavien
Flavien

Reputation: 8117

Editing a line of a configuration file from shell

Given a configuration file, such as sshd_config:

[...]
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
[...]

I would like to write a command that lets me set a configuration setting. For example, I want to set PasswordAuthentication to no. If the entry already exists, I want to replace it, if it doesn't, I want to add it at the end of the file.

How can I do that from the shell?

Upvotes: 1

Views: 134

Answers (2)

Vijay
Vijay

Reputation: 67211

awk '{if($1~/PasswordAuthentication/){flag=1;if($2~/yes/)$2="no";print $0}else{print}} END{if(flag!=1)print "PasswordAuthentication no"}' temp

Upvotes: 0

dogbane
dogbane

Reputation: 274532

You can use awk to do this. Here is a script I wrote:

$ cat setProp.sh
#!/bin/sh

propFile=$1
key=$2
value=$3

awk -v "key=$key" -v "value=$value" '{
    if($1==key) {
        found=1
        print $1" "value
    } else {
        print
    }
}
END {
    if(!found) print key" "value
}' $propFile

Usage:

$ setProp.sh myfile RhostsRSAAuthentication no
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10

Upvotes: 2

Related Questions