For the former:
# run sed, capture any output
var1="$(sed -i "/connection.username/c connection.username=$name" $search)"
For the latter:
# run sed, discard all output but keep exit status
sed -i "/connection.username/c connection.username=$name" $search >/dev/null 2>&1
That said, valid()
is... strange, to say the least. I would write it as
# valid label [status]
# check status ($? if not provided) and log success/failure
function valid {
if [[ ${2-$?} == 0 ]]; then
echo "$1 : status : OK"
else
echo "$1 : status : ERROR"
fi
}
Actually, I would do it a bit differently from the start:
# log label command [arguments...]
# run command, output success/failure to stderr. If label is empty, use the
# command name: 'log "" echo hi' uses 'echo' as the label.
# log entries look like
# label1 : status : OK
# label2 : status : ERROR
# Error output from foo:
# Baz is broken; fix and try again.
log() {
# save off label
local label="${1:-$2}"
shift # this removes $1 and shifts $2... to $1... so "$@" works later
# run command, capture output
# $(command) runs 'command' and substitutes its output
# "$@" preserves quoting; $* would turn argument "foo bar" into two
# arguments foo bar
err="$("$@")"
if [[ $? == 0 ]]; then
status=OK
else
status=ERROR
fi
echo "$label : status : $status" >&2 # standard error
if [[ $status == ERROR ]]; then
# log output from command, indented for clarity
echo "Error output from $2:"
echo "$err" | sed 's/^/ /' >&2
fi
}
save() {
# this sed command is pedantically correct; if GNU sed lets you
# do single-line 'c' commands as in the original, then go for it.
# The backslash-return after the label argument is just for clarity;
# 'log "foo" bar' works just as well.
log "adding database ip" \
sed -i "/:@/c\\
connection.url=jdbc:oracle:thin:@$ip:1521:$dataBase\\
." "$search"
# using the original (GNU?) sed syntax
log "adding database SID" \
sed -i "/connection.username/c connection.username=$name" "$search"
}
save
I would also include a timestamp and program ID, etc. in a real program.
You should probably explore the Advanced Bash Scripting Guide to learn more about writing shell scripts. The UNIX Programming Environment's shell programming chapters don't cover bash
extensions to the original Bourne shell, but are still useful for learning the "zen" of shell scripting.
valid()
function is missing}
. What do you want to achieve? Replacing lines matching:@
withconnec...database
? Or replace occurences of:@
in string$search
by the text?