Why isn't chdir happening for this rc.d script? - freebsd

I've hit a wall trying to understand why the ${name}_chdir variable is not working for me. Finally, after letting my script run with -xv, I see that the cd command is not even being run in my case. Here is my script:
#!/bin/sh
set -xv
exec 1>/tmp/awning.rclog 2>&1
# REQUIRE: NETWORKING LOGIN DAEMON
# KEYWORD: shutdown
. /etc/rc.subr
name="awning"
rcvar="awning_enable"
awning_chdir="/usr/sbin/awning"
pidfile="/var/run/awningd.pid"
procname="daemon"
# -f flag is to redirect stdin/stdout/stderr to /dev/null to prevent node from crashing
# on system-startup
start_cmd="/usr/sbin/daemon -r -P ${pidfile} -f -u pierre /usr/sbin/awning/intro.js"
command="/usr/sbin/daemon -r -P ${pidfile} -f -u pierre /usr/sbin/awning/intro.js"
load_rc_config $name
run_rc_command "$1"
At first I was only using start_cmd, but then I read in rc.subr the following:
${name}_chdir
Directory to cd to before running _command_, if
${name}_chroot is not provided.
so I thought maybe things were getting mixed up, so i added the command=.... bit, and removed the start_cmd=.... line, and still no success. Here's the relevant "doit" portion of the output which was saved from running the script with -xv:
+ _chdir=/usr/sbin/awning _chroot='' _nice='' _user='' _group='' _groups='' _fib='' _env='' _prepend='' _login_class=daemon _oomprotect=''
+ [ -n '' ]
+ [ -z yes ]
+ [ start '!=' start ]
+ [ -n awning_enable -a start '!=' rcvar -a start '!=' stop -a start '!=' describe ]
+ checkyesno awning_enable
+ eval '_value=$awning_enable'
+ _value=YES
+ debug 'checkyesno: awning_enable is set to YES.'
+ return 0
+ [ start '=' start -a -z yes -a -n '' ]
+ eval '_cmd=$start_cmd' '_precmd=$start_precmd' '_postcmd=$start_postcmd'
+ _cmd='/usr/sbin/daemon -r -P /var/run/awningd.pid -f -u pierre /usr/sbin/awning/intro.js' _precmd='' _postcmd=''
+ [ -n '/usr/sbin/daemon -r -P /var/run/awningd.pid -f -u pierre /usr/sbin/awning/intro.js' ]
+ _run_rc_precmd
+ check_required_before start
+ local _f
+ return 0
+ [ -n '' ]
+ check_required_after start
+ local _f _args
+ return 0
+ return 0
+ _run_rc_doit '/usr/sbin/daemon -r -P /var/run/awningd.pid -f -u pierre /usr/sbin/awning/intro.js '
+ debug 'run_rc_command: doit: /usr/sbin/daemon -r -P /var/run/awningd.pid -f -u pierre /usr/sbin/awning/intro.js '
+ eval '/usr/sbin/daemon -r -P /var/run/awningd.pid -f -u pierre /usr/sbin/awning/intro.js '
+ /usr/sbin/daemon -r -P /var/run/awningd.pid -f -u pierre /usr/sbin/awning/intro.js
+ _return=0
+ [ 0 -ne 0 ]
+ return 0
+ _run_rc_postcmd
+ [ -n '' ]
+ return 0
+ return 0
_chdir is being set properly, but it's never used for anything. Honestly it looks like those variables (_chdir, _chroot, etc) should actually be awning_chdir, awning_chroot, etc...
What could be going on?
I'm running version 11.0-RELEASE-p2

After stepping through /etc/rc.subr, I learned (the hard way) that command= needs to literally be a single command. There's a test done on it ([ ! -x $command ]) which fails even for a command with options and no arguments. I had to split apart the options I was passing daemon, and its single argument /usr/sbin/awning/intro.js into a separate variable: command_args=, which solved the issue.

Related

using curl with -d param1=value1 seems not work properly

I have a shell Unix running every hour (crontab on CentOS 7).
Inside that shell, a loop read and proceed treatment for all new files find in a defined folder.
At the end of each files's treatment a CURL command is send with some parameters, for example :
curl https://aaaaaa.com/website -d param1=value1 -d param2=value2 ....
Each time the shell is run by crontab, the 1st CURL is correctly converted to a true URL and received by Apache/Tomcat, but all the others are bad. In fact the 2nd and the following CURLs seem not converted in the correct format like
https://aaaaaa.com/website?param1=value1&param2=value2
but they are sent like
https://aaaaaa.com/website -d param1=value1 -d param2=value2
So the website is unable to treat the parameters properly.
Why the 1st command is correctly converted to a correct URL format and not the following ?
EDIT - EDIT
The part of shell :
#!/bin/bash
...
#======================================================
# FUNCTIONS
#======================================================
UpdateStatus () {
CMD_CURL="${URL_WEBSITE} -d client=CLIENT -d site=TEST -d produit=MEDIASFILES -d action=update"
CMD_CURL="${CMD_CURL} -d codecmd=UPDATE_MEDIA_STATUS"
CMD_CURL="${CMD_CURL} -d idmedia=$4"
CMD_CURL="${CMD_CURL} -d idbatch=$3"
CMD_CURL="${CMD_CURL} -d statusmedia=$2"
if [[ ! -z "$5" ]]; then
CMD_CURL="${CMD_CURL} -d filename=$5"
fi
echo " ${CMD_CURL}" >> $1
CURL_RESULT=`curl -k ${CMD_CURL}`
CURL_RESULT=`echo ${CURL_RESULT} | tr -d ' '`
echo " Result CURL = ${CURL_RESULT}" >> $1
if [ "${CURL_RESULT}" = "OK" ]; then
return 0
fi
return 1
}
#======================================================
# MAIN PROGRAM
#======================================================
echo "----- Batch in progress : `date '+%d/%m/%y - %H:%M:%S'` -----"
for file in $( ls ${DIR_FACTORY_BATCHFILES}/*.batch )
do
...
old_IFS=$IFS
while IFS=';' read <&3 F_STATUS F_FILEIN F_TYPE F_CODE F_ID F_IDPARENT F_TAGID3 F_PROF F_YEARMEDIA F_DATECOURS F_TIMEBEGINCOURS F_LANG || [[ -n "$F_STATUS $F_FILEIN $F_TYPE $F_CODE $F_ID $F_IDPARENT $F_TAGID3 $F_PROF $F_YEARMEDIA $F_DATECOURS $F_TIMEBEGINCOURS $F_LANG" && $F_STATUS ]];
do
...
UpdateStatus ${LOG_FILENAME} ${STATUS_ERROR} ${F_ID} ${F_IDPARENT}
...
done 3< $file
IFS=$Old_IFS
...
done
You need to provide the "-d" flags and values before the URL so:
curl -d param1=value1 -d param2=value2 https://aaaaaa.com/website
Moreover, this command is going to send the parameters/values as POST parameters, not query parameters. You can use the "-G" flag, possibly combined with "--url-encode" to send as query parameters, see:
https://unix.stackexchange.com/questions/86729/any-way-to-encode-the-url-in-curl-command

passing double-quotes through weka machine learning

I am using CLI of Weka, namely, Primer and I have tried many different combo of passing several argument with no success. When I pass sth like this:
weka_options=("weka.classifiers.functions.SMOreg -C 1.0 -N 0")
the program runs with no issue, but passing something like this:
weka_options=("weka.classifiers.functions.SMOreg -C 1.0 -N 0 -I \"weka.classifiers.functions.supportVector.RegSMOImproved -L 1.0e-3 -W 1 -P 1.0e-12 -T 0.001 -V\" -K \"weka.classifiers.functions.supportVector.NormalizedPolyKernel -C 250007 -E 8.0\"")
with/withOut escape character and even single quoted `, brings me error in my bash scripts:
bash ./weka.sh "$sub_working_dir" $train_percentage "$weka_options" $files_string > $predictions
where weka.sh contains:
java -Xmx1024m -classpath ".:$WEKAPATH" $weka_options -t "$train_set" -T "$test_set" -c 53 -p 53
Here is what I get:
---Registering Weka Editors---
Trying to add database driver (JDBC): jdbc.idbDriver - Error, not in CLASSPATH?
Weka exception: Can't open file No suitable converter found for '0.001'!.
Can anyone pinpoint the issue?
Updated question: here is the codes:
# Usage:
#
# ./aca2_explore.sh working-dir datasets/*
# e.g.
# ./aca2_explore.sh "aca2-explore-working-dir/" datasets/*
#
# Place this script in the same folder as aca2.sh and the folder containing the datasets.
#
#
# Please note that:
# - All the notes contained in aca2.sh apply
# - This script will erase the contents of working-dir
# to properly sort negative floating numbers, independently of local language options
export LC_ALL=C
# parameters parsing
output_directory=$1
first_file_index=2
files=${#:$first_file_index}
# global constants
datasets=$(($# - 1))
output_row=$(($datasets + 3))
output_columns_range="2-7"
learned_model_mae_column=4
results_learned_model_mae_column=4
# parameters
working_dir="$output_directory"
if [ -d "$working_dir" ];
then
rm -r "$working_dir"
fi
mkdir "$working_dir"
sub_working_dir="$working_dir""aca2-explore-sub-working-dir/"
path_to_results_file="$sub_working_dir""results.csv"
train_percentage=25
logfile="$working_dir""aca2_explore_log.csv"
echo "" > "$logfile"
reduced_log_header="Options,average_test_set_speedup,null_model_mae,learned_model_mae,learned_model_rmse,mae_ratio,R^2"
reduced_logfile="$working_dir""aca2_explore_reduced_log.csv"
echo "$reduced_log_header" > "$reduced_logfile"
sorted_reduced_logfile="$working_dir""aca2_explore_sorted_reduced_log.csv"
weka_options_list=(
"weka.classifiers.functions.LinearRegression -S 0 -R 1.0E-8"
"weka.classifiers.functions.MultilayerPerceptron -L 0.3 -M 0.2 -N 100 -V 0 -S 0 -E 20 -H a"
"weka.classifiers.meta.AdditiveRegression -S 1.0 -I 10 -W weka.classifiers.trees.DecisionStump"
"weka.classifiers.meta.Bagging -P 100 -S 1 -num-slots 1 -I 10 -W weka.classifiers.trees.REPTree -- -M 2 -V 0.001 -N 3 -S 1 -L -1 -I 0.0"
"weka.classifiers.meta.CVParameterSelection -X 10 -S 1 -W weka.classifiers.rules.ZeroR"
"weka.classifiers.meta.MultiScheme -X 0 -S 1 -B \"weka.classifiers.rules.ZeroR \""
"weka.classifiers.meta.RandomCommittee -S 1 -num-slots 1 -I 10 -W weka.classifiers.trees.RandomTree -- -K 0 -M 1.0 -V 0.001 -S 1"
"weka.classifiers.meta.RandomizableFilteredClassifier -S 1 -F \"weka.filters.unsupervised.attribute.RandomProjection -N 10 -R 42 -D Sparse1\" -W weka.classifiers.lazy.IBk -- -K 1 -W 0 -A \"weka.core.neighboursearch.LinearNNSearch -A \"weka.core.EuclideanDistance -R first-last\"\""
"weka.classifiers.meta.RandomSubSpace -P 0.5 -S 1 -num-slots 1 -I 10 -W weka.classifiers.trees.REPTree -- -M 2 -V 0.001 -N 3 -S 1 -L -1 -I 0.0"
"weka.classifiers.meta.RegressionByDiscretization -B 10 -K weka.estimators.UnivariateEqualFrequencyHistogramEstimator -W weka.classifiers.trees.J48 -- -C 0.25 -M 2"
"weka.classifiers.meta.Stacking -X 10 -M \"weka.classifiers.rules.ZeroR \" -S 1 -num-slots 1 -B \"weka.classifiers.rules.ZeroR \""
"weka.classifiers.meta.Vote -S 1 -B \"weka.classifiers.rules.ZeroR \" -R AVG"
"weka.classifiers.rules.DecisionTable -X 1 -S \"weka.attributeSelection.BestFirst -D 1 -N 5\""
"weka.classifiers.rules.M5Rules -M 4.0"
"weka.classifiers.rules.ZeroR"
"weka.classifiers.trees.DecisionStump"
"weka.classifiers.trees.M5P -M 4.0"
"weka.classifiers.trees.RandomForest -I 100 -K 0 -S 1 -num-slots 1"
"weka.classifiers.trees.RandomTree -K 0 -M 1.0 -V 0.001 -S 1"
"weka.classifiers.trees.REPTree -M 2 -V 0.001 -N 3 -S 1 -L -1 -I 0.0")
files_string=""
for file in ${files[#]}
do
files_string="$files_string""$file"" "
done
#echo $files_string
for weka_options in "${weka_options_list[#]}"
do
echo "$weka_options"
echo "$weka_options" >> "$logfile"
bash ./aca2.sh "$sub_working_dir" $train_percentage "$weka_options" $files_string
cat "$path_to_results_file" >> "$logfile"
result_columns=$(tail -n +"$output_row" "$path_to_results_file" | head -1 | cut -d, -f"$output_columns_range")
echo "$weka_options"",""$result_columns" >> "$reduced_logfile"
echo "" >> "$logfile"
done
tail -n +2 "$reduced_logfile" > "$sorted_reduced_logfile"
sort --field-separator=',' --key="$results_learned_model_mae_column" "$sorted_reduced_logfile" -o "$sorted_reduced_logfile"".tmp"
echo "$reduced_log_header" > "$sorted_reduced_logfile"
cat "$sorted_reduced_logfile"".tmp" >> "$sorted_reduced_logfile"
rm "$sorted_reduced_logfile"".tmp"
where the file aca2.sh is:
#!/bin/bash
# Run this script as ./script.sh working-directory train-set-filter-percentage "weka_options" datasets/*
#
# e.g.
# Place this script in a folder together with a directory containing your datasets. Call then the script as
# ./aca2.sh "aca2-working-dir/" 25 "weka.classifiers.functions.LinearRegression -S 0 -R 1.0E-8" datasets_folder/*
#
# NOTE: the script will erase the content of working-directory
# for correct behaviour $WEKAHOME environment variable must be set to the folder containing weka.jar, otherwise modify the call to the weka classifier below
#
# To define the error measures used in this script, I made use of some of the notions found in this article:
# http://scott.fortmann-roe.com/docs/MeasuringError.html
# parameters parsing
output_directory=$1
train_set_percentage=$2
if [ $train_set_percentage -lt 1 ] || [ $train_set_percentage -gt 100 ];
then
echo "Invalid train set percentage: "$train_set_percentage
exit 1
fi
weka_options=$3
first_file_index=4
files=${#:$first_file_index}
# global constants
predictions_characters_range_value="23-28"
predictions_characters_range_error="34-39"
tmp_dir="$output_directory"
if [ -d "$tmp_dir" ];
then
rm -r "$tmp_dir"
fi
mkdir "$tmp_dir"
results_header="testfile,average_test_set_speedup,null_model_mae,learned_model_mae,learned_model_rmse,mae_ratio,R^2"
results_file=$tmp_dir"results.csv"
echo "$results_header" > "$results_file"
arff_header="% ARFF conversion of CSV dataset
#RELATION program
#ATTRIBUTE ...
#DATA"
# global constants
datasets_per_program=5
entries_per_dataset=128
train_set_instances_to_select=$((datasets_per_program*entries_per_dataset*train_set_percentage/100))
all_prediction="$tmp_dir""all_predictions.txt"
count=0
prediction_efficiency_ideal_avg=0
arff_header_file="$tmp_dir""arff_header.txt"
echo "$arff_header" > "$arff_header_file"
count=0
for filename in ${files[#]}
do
echo "Test set: $filename"
echo "$filename" >> "$all_prediction"
cur_dir="$tmp_dir$filename.dir/"
mkdir -p $cur_dir
testfile=$filename
train_set="$cur_dir""train_set.arff"
echo "$arff_header" > $train_set
selected_train_subset="$cur_dir""selected_train_subset.csv"
for trainfile in ${files[#]}
do
if [ "$trainfile" != "$testfile" ]; then
# filter train set to feed only top 25% for model generation
sort --field-separator=',' --key=53 "$trainfile" -o "$selected_train_subset"
head -$train_set_instances_to_select "$selected_train_subset" >> $train_set
fi
done
test_set="$cur_dir""test_set.arff"
#echo "$arff_header" > $test_set
cp "$testfile" "$test_set"
# This file will contain the full configuration space dataset relative to the test program
complete_test_set="$cur_dir""complete_test_set.csv"
cp "$test_set" "$complete_test_set"
sort --field-separator=',' --key=53 "$test_set" -o "$test_set"
head -8 "$test_set" > "$test_set"".tmp"
mv "$test_set"".tmp" "$test_set"
cur_prediction="$cur_dir""cur_prediction.tmp"
# generate basis for predicted test set file by copying the actual test set, removing speedups
predicted_test_set="$cur_dir""predicted_test_set.csv"
cp "$test_set" "$predicted_test_set"
cut -d, -f53 --complement "$predicted_test_set" > "$predicted_test_set"".tmp"
mv "$predicted_test_set"".tmp" "$predicted_test_set"
cat "$arff_header_file" "$test_set" > "$test_set"".tmp"
mv "$test_set"".tmp" "$test_set"
java -Xmx1024m -classpath ".:$WEKAHOME/weka.jar:$WEKAJARS/*" $weka_options -t "$train_set" -T "$test_set" -c 53 -p 53 | tail -n +6 | head -8 > "$cur_prediction"
predictions_file="$cur_dir""predictions.csv"
cut -c"$predictions_characters_range_value" "$cur_prediction" | tr -d " " > "$predictions_file"
paste -d',' "$actual_speedups" "$predictions_file" > "$predictions_file"".tmp"
mv "$predictions_file"".tmp" "$predictions_file"
done
You almost have this right. You were trying to do the right thing it looks like (or just getting accidentally close).
You cannot use a string for arbitrarily quoted arguments (this is Bash FAQ 050).
You need to use an array instead. But you need an array with a separate element for each argument. Not just one argument.
weka_options=(weka.classifiers.functions.SMOreg -C 1.0 -N 0)
or
weka_options=(weka.classifiers.functions.SMOreg -C 1.0 -N 0 -I "weka.classifiers.functions.supportVector.RegSMOImproved -L 1.0e-3 -W 1 -P 1.0e-12 -T 0.001 -V" -K "weka.classifiers.functions.supportVector.NormalizedPolyKernel -C 250007 -E 8.0")
(I assume the string weka.classifiers.functions.supportVector.RegSMOImproved -L 1.0e-3 -W 1 -P 1.0e-12 -T 0.001 -V is the argument to the -I flag and that the string weka.classifiers.functions.supportVector.NormalizedPolyKernel -C 250007 -E 8.0 is the argument to the -K flag. If that's not the case then those quotes likely want to get removed also.)
And then when you use the array you need to use "${weka_options[#]}" to get the elements of the array as individual quoted words.
java -Xmx1024m -classpath ".:$WEKAPATH" "${weka_options[#]}" -t "$train_set" -T "$test_set" -c 53 -p 53

How to change file permission while doing ssh in shell

I am using the below codes to change some file permissions:
encrypt=`sed -n '/:/,$p' $FILE_PATH_1 | cut -d':' -f2 | tr -d ' '`
local listOfPasswordChangeWS=`$SMANAGER_SCRIPT status service PasswordChangeWS | cut -f 2 -d ":"`
for node in $listOfPasswordChangeWS ; do
ssh -q $i "cp /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties.original"
ssh -q $i "sed -i '/Password/c\com.ibm.CORBA.loginPassword=ENC($encrypt)' /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties "
**ssh -q $i "chown -c omc:sysop /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties ; chmod 640 /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties"**
# INCR=$?
INCR=$?
if [ "INCR" == "0" ] ; then
NewIncr++
fi
done
I want to check the exit status but since it is in for loop i am not able to get value 0 or 1 instead it is returning value 255. My query is:
1. How can I check the exit status of chown -c command (Remember i am doing ssh)
2. How can I check whether my file permission has been changed to omc:sysop
Try this:
if ssh $HOST 'chown -c omc:sysop /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties ; chmod 640 /opt/oss/NSN-mf_swp/smx/mf-conf/was-cred.properties' < /dev/null
if [ $? -eq 0 ]; then
echo SUCCESS
else
echo FAIL
fi

Bash: An IF statement returns unexpected value, can you find the reason?

I've wrote a script which automatically downloads and installs Nagios NRPE on CentOS machines.
The relevant portion of the script is:
read -r -p "How would you like to configure the NRPE daemon? [X]inetd / Standalone [D]aemon " DMN
if [ "DMN" = "x" -o "DMN" = "X" ];
then
DMNMODE="xinetd"
cat << EOF > $XINETDFILE
service nrpe
{
flags = REUSE
type = UNLISTED
port = $NRPEPORT
socket_type = stream
wait = no
user = $NGUSER
group = $NGGROUP
server = /usr/sbin/nrpe
server_args = -c $NRPECFG --inetd
log_on_failure += USERID
disable = no
only_from = 127.0.0.1 $NAGIOSSRV
}
EOF
/etc/init.d/xinetd restart
elif [ "DMN" = "d" -o "DMN" = "D" ];
then
chkconfig nrpe on ; $NRPESVC start
DMNMODE="daemon"
fi
function CheckInstMode {
if [ "DMNMODE" = "daemon" ];
then
$NRPESVC restart
else
$XINETDSVC restart
fi
}
read -r -p "Would you like to pull NRPE plugins from Nagios server? [y/n]" ANS1
if [ $ANS1 = "y" ];
then
if [ $ARCH = "64" -a $NGSARCH = "64" ] ;
then scp root#$NAGIOSSRV:$NGPLUGINS64/* $NGPLUGINS64/
chown -R $NGUSER.$NGGROUP $NGPLUGINS64
CheckInstMode
elif [ "$ARCH" = "64" -a "$NGSARCH" = "32" ] ;
then scp root#$NAGIOSSRV:$NGPLUGINS32/* $NGPLUGINS64/
chown -R $NGUSER.$NGGROUP $NGPLUGINS64
CheckInstMode
elif [ "$ARCH" = "32" -a "$NGSARCH" = "32" ] ;
then scp root#$NAGIOSSRV:$NGPLUGINS32/* $NGPLUGINS32/
chown -R $NGUSER.$NGGROUP $NGPLUGINS32
CheckInstMode
elif [ "$ARCH" = "32" -a "$NGSARCH" = "64" ] ;
then scp root#$NAGIOSSRV:$NGPLUGINS64/* $NGPLUGINS32/
chown -R $NGUSER.$NGGROUP $NGPLUGINS32
CheckInstMode
fi
fi
The idea behind the function is to check which installation mode was chosen and restart /etc/init.d/xinetd if Xinetd was chosen or restart /etc/init.d/nrpe if NRPE was chosen.
I've ran the script in debug mode (sh -x script) and this is the output:
+ case $ARCH in
+ echo 'Configuring /etc/nagios/nrpe.cfg'
Configuring /etc/nagios/nrpe.cfg
+ cat
+ echo 'Adding nagios user to /etc/sudoers'
Adding nagios user to /etc/sudoers
+ echo 'Defaults:nagios !requiretty'
+ echo 'nagios ALL = NOPASSWD:/usr/lib64/nagios/plugins/*'
+ echo 'Setting ownership of nagios and nagios plugins folders to nagios user'
Setting ownership of nagios and nagios plugins folders to nagios user
+ chown -R nagios.nagios /etc/nagios
+ chown -R nagios.nagios /usr/lib64/nagios/plugins
+ read -r -p 'How would you like to configure the NRPE daemon? [X]inetd / Standalone [D]aemon ' DMN
How would you like to configure the NRPE daemon? [X]inetd / Standalone [D]aemon x
+ '[' DMN = x -o DMN = X ']'
+ '[' DMN = d -o DMN = D ']'
+ read -r -p 'Would you like to pull NRPE plugins from Nagios server? [y/n]' ANS1
Would you like to pull NRPE plugins from Nagios server? [y/n]y
+ '[' y = y ']'
+ '[' 64 = 64 -a 64 = 64 ']'
+ scp 'root#IP:/usr/lib64/nagios/plugins/*' /usr/lib64/nagios/plugins/
1 100% 71 0.1KB/s 00:00
Back-check_services.pl 100% 2485 2.4KB/s 00:00
cacticpu.sh 100% 189 0.2KB/s 00:00
check_apt 100% 99KB 99.4KB/s 00:00
check_breeze 100% 2253 2.2KB/s 00:00
check_by_ssh 100% 41KB 40.6KB/s 00:00
check_clamd 100% 46KB 46.5KB/s 00:00
+ chown -R nagios.nagios /usr/lib64/nagios/plugins
+ CheckInstMode
+ '[' DMNMODE = daemon ']'
+ /etc/init.d/nrpe restart
Shutting down nrpe: [ OK ]
Starting nrpe: [ OK ]
+ stat --format=%Y /etc/passwd
+ chmod +x /usr/local/share/applications/file
+ read -r -p 'Would you like to test NRPE? [y/n]' ANS2
Would you like to test NRPE? [y/n]
As you can see the DMNMODE variable which is expected to be xinetd is daemon instead, even though my input for the question of xinetd or daemon was "x".
This causes the script to restart nrpe even if xinetd was selected, can you please tell me what I'm doing wrong?
Edit #1:
I still get an unexpected result from variable $DMNMODE, Here's the debug run:
How would you like to configure the NRPE daemon? [X]inetd / Standalone [D]aemon x
+ [[ x = [Xx] ]]
+ DMNMODE=xinetd
+ cat
+ /etc/init.d/xinetd restart
Stopping xinetd: [ OK ]
Starting xinetd: [ OK ]
+ read -r -p 'Would you like to pull NRPE plugins from Nagios server? [y/n]' ANS1
Would you like to pull NRPE plugins from Nagios server? [y/n]y
+ '[' y = y ']'
+ '[' 64 = 64 -a 64 = 64 ']'
+ scp 'root#IP:/usr/lib64/nagios/plugins/*' /usr/lib64/nagios/plugins/
1 100% 71 0.1KB/s 00:00
Back-check_services.pl 100% 2485 2.4KB/s 00:00
cacticpu.sh 100% 189 0.2KB/s 00:00
check_apt 100% 99KB 99.4KB/s 00:00
negate 100% 30KB 29.7KB/s 00:00
plugins.pm 100% 1939 1.9KB/s 00:00
+ chown -R nagios.nagios /usr/lib64/nagios/plugins
+ CheckInstMode
+ '[' xinetd = daemon ']'
+ /etc/init.d/nrpe restart
Shutting down nrpe: [ OK ]
Starting nrpe: [ OK ]
+ stat --format=%Y /etc/passwd
+ chmod +x /usr/local/share/applications/file
+ read -r -p 'Would you like to test NRPE? [y/n]' ANS2
My question is... Why does the function return the wrong value? if you scroll up you can see that I typed X in the question which means that DMNMODE variable is set to xinetd and not nrpe... can you try and find the problem please?
Your help is much appreciated!
Itai
The $DMN variable references are missing $ signs.
if [ "$DMN" = "x" -o "$DMN" = "X" ];

Command aliases in my script

I am creating a script for copying files or directory with a date attached to its name, for example if the file name is test it will be test-20130901.bkup
and this is my script
#!/usr/bin/bash
set -x
getopts fd TYPE
[ $TYPE = "d" ] && alias cp="cp -r"
backup_error() {
echo "${0##*/}: $1"
exit -1
}
typeset -r FROM_DIR=$2 TO_DIR=$3
if [ ! -e $FROM_DIR -a ! -d $FROM_DIR ] || [ ! -e $TO_DIR -a ! -d $TO_DIR ]
then
backup_error "One of the directories isn't exist or it maybe a file";
fi
typeset -r DATE=$(date "+%Y%m%d")
for filename in $FROM_DIR/*
do
if [ -$TYPE $filename ]
then
cp $filename $TO_DIR/${filename##*/}-$DATE.bkup
fi
done
unalias cp
In the script I check if the user wants to run the script on files only or on directories only.
-f for files only
-d for directories only
[ $TYPE = "d" ] && alias cp="cp -r", this line to check if the script runs for directory I must use cp -r so I make an alias for cp to be cp -r
but when I use set -x to debug I find the when a user use -d option the cp command in the if still the original one not the alias.
Debugging:
> ./backup.sh -d . .
+ getopts fdb TYPE
+ '[' d = d ']'
+ alias 'cp=cp -r'
+ typeset -r FROM_DIR=. TO_DIR=.
+ '[' '!' -e . -a '!' -d . ']'
+ '[' '!' -e . -a '!' -d . ']'
++ date +%Y%m%d
+ typeset -r DATE=20130901
+ '[' -d ./backup.sh ']'
+ '[' -d ./dir1 ']'
+ cp ./dir1 ./dir1-20130901.bkup
cp: ./dir1: is a directory
+ '[' -d ./file1 ']'
+ '[' -d ./file2 ']'
+ '[' -d ./test.sh ']'
+ unalias cp
Use a function instead:
if [[ $TYPE == d ]]; then
function cp {
command cp -r "$#"
}
fi
And when in Bash, [[ ]] is recommended over test or [ ].
Also quote please quote your variables properly between "" to prevent word splitting and unexpected pathname expansion.
Other caveats:
exit -1 ## exit can only accept 8-bit integral values from 0 to 255. -1 here is orthodox and is equivalent to 255.
You should quote the variables here or use [[ ]]:
if [[ ! -e $FROM_DIR && ! -d $FROM_DIR ]] || [[ ! -e $TO_DIR && ! -d $TO_DIR ]]
if [ "-$TYPE" "$filename" ] ## for custom operators, test is better: test "-$TYPE" "$filename"
cp "$filename" "$TO_DIR/${filename##*/}-$DATE.bkup"
for filename in "$FROM_DIR"/*
Lastly make sure you run your script as:
bash script.sh -f from_dir to_dir
# Or
bash script.sh -d from_dir to_dir

Resources