Command not found in elif comparison > bash - bash

For some reason commands are not running after the first if statement.
"/usr/local//backup.sh: sleep: not found" for example..
The first if statement goes like:
if [ "$command" == "start -c" ]; then
echo -e "${ORANGE}Starting website backup...${E}"
sleep 1
DT=`date +%Y-%m-%d`
echo -e "${ORANGE}Started backup at $DT ${E}"
sleep 1
tar -zcvf web-$DT.tar.gz /usr/local/www/nginx
echo -e "${ORANGE}Compatced files, moving to backup directory${E}"
sleep 1
mv web-$DT.tar.gz $PATH/web-$DT.tar.gz
echo -e "${CYAN}Moved to backups ($PATH/web-$DT.tar.gz)\nDo you want to upload to ftp?${E}\n${CYAN} 'y' or 'n'?${E}"
read answer
if [ "$answer" == "y" ]; then
echo -e "${ORANGE}Uploading to ftp server...${E}"
sleep 1
if ftp -in -u ftp://$USER:$PASS#$HOST/Backups/f $PATH/web-$DT.tar.gz; then
echo -e "${GREEN}Uploaded! Bye!${E}"
else
echo -e "${ORANGE}Couldn't upload with ftp command, trying with curl...${E}"
sleep 1
curl -T "$PATH/web-$DT.tar.gz" -u $USER:$PASS ftp://$HOST/Backups/f/
echo -e "${GREEN}Uploaded! Bye!${E}"
fi
else
echo -e "${GREEN}Bye!${E}"
fi
Everything works fine inside this statement, however, after the elif compassion it just doesn't.
Here's the problematic code:
elif [ "$command" == "start -d" ]; then
echo -e "${ORANGE}Starting database backup...${E}"
sleep 1
DT=`date +%Y-%m-%d`
echo -e "${ORANGE}Started backup at $DT ${E}"
sleep 1
umask 177
echo -e "${ORANGE}Dumping database 'account'\n${E}"
mysqldump --user=$DBUSER --password=$DBPASS --host=$HOST account > $PATH/account-$DT.sql
sleep 1
echo -e "${ORANGE}Dumping database 'game'\n${E}"
mysqldump --user=$DBUSER --password=$DBPASS --host=$HOST game > $PATH/game-$DT.sql
sleep 1
echo -e "${ORANGE}Dumping database 'forum'\n${E}"
mysqldump --user=$DBUSER --password=$DBPASS --host=$HOST forum > $PATH/forum-$DT.sql
sleep 1
echo -e "${CYAN}Moved to backups ($PATH/<database-date>.sql)\nDo you want to upload to ftp?${E}\n${CYAN} 'y' or 'n'?${E}"
read answer
if [ "$answer" == "y" ]; then
echo -e "${ORANGE}Uploading to ftp server...${E}"
sleep 1
curl -T "$PATH/account-$DT.sql" -u $USER:$PASS ftp://$HOST/Backups/f/Databases/
curl -T "$PATH/game-$DT.sql" -u $USER:$PASS ftp://$HOST/Backups/f/Databases/
curl -T "$PATH/forum-$DT.sql" -u $USER:$PASS ftp://$HOST/Backups/f/Databases/
sleep 1
echo -e "${GREEN}Uploaded! Bye!${E}"
else
echo -e "${GREEN}Bye!${E}"
fi
and then I just ended it..
else
echo -e "${RED}Sorry! Not found${E}"
fi
As you can see there's spaces in the if statements and all of that, so what's wrong with this??
I've the #!/bin/bash up top as well, all the variables exist too.

You seem to have overwritten the value of the PATH variable at some point in your code. The shell needs that variable in order to know where to find programs like sleep (Hence the "not found" error). Name your path variable something else.

Related

How to supply password from shell script without using expect command

I'm writing a bash script to stop start my postgres DB service. Initially I succeeded in creating one, but as soon I enabled SSL certificate it prompts to enter the phrase password.
I know the easiest solution is to use expect , but in my environment i am not authorized to use it.
Can someone help me out in scripting as to how can I supply the PEM PHRASE password without a user intervention.
This is what I have worked so far.
-bash-4.2$ cat start_postgres_db.sh
cd `dirname $0`
. `dirname $0`/parameter.env
${POSTGREBIN}/pg_ctl -D ${POSTGREDATAPATH} start -w
while true
do
sleep 1
loopcnt=0
loopcnt=`expr ${loopcnt} + 1`
PRCCNT=`ps -ef | grep ${DBEXENAME} | grep -v grep|wc -l`
if [ ${PRCCNT} -eq 1 ]
then
echo "PostgreSQL process started sucessfully"
exit
fi
if [ ${loopcnt} -gt 11 ]
then
echo "PostgreSQL process not started successfully"
echo "su to postgres and run ${POSTGREBIN}/pg_ctl -D ${POSTGREDATAPATH} restart"
exit
fi
done
Execution:
bash-4.2$ ./start_postgres_db.sh
waiting for server to start....Enter PEM pass phrase:.........
You can provide a password to pg_ctl as argument on the command line with the option -P. I will assume it is contained in the variable ${POSTGREPASSWORD}.
start_postgres_db.sh
cd `dirname $0`
. `dirname $0`/parameter.env
${POSTGREBIN}/pg_ctl start -w -D ${POSTGREDATAPATH} -P ${POSTGREPASSWORD}
while true; do
sleep 1
(( loopcnt++ ))
PRCCNT=$(ps -ef | grep ${DBEXENAME} | grep -v grep | wc -l)
if [ ${PRCCNT} -eq 1 ]; then
echo "PostgreSQL process started sucessfully"
exit 0
fi
if [ ${loopcnt} -gt 11 ]; then
echo "PostgreSQL process not started successfully"
echo "su to postgres and run ${POSTGREBIN}/pg_ctl -D ${POSTGREDATAPATH} restart"
exit 1
fi
done

Multiple if's and read lines ignored

I have written a script containing various user queries and conditions. First, I want the user to be asked if the changelog should be displayed. Then the user is asked if he should do the update. But here is the problem, after the first condition and the display of the changelog, the next query is simply skipped. Why is that?
if version_gt $serverversion $version; then
echo -e "\e[34m#########################################################"
echo -e "\e[34mThere is a new version. Do you want to see the Changelog?"
echo -e "\e[34m#########################################################"
read -p "Yes(y)/No(n) " -n 1 -r changelog
if [[ $changelog =~ ^[Yy]$ ]]
then
curl --silent "$changelogurl"
fi
echo -e "\e[34m#########################################################"
echo -e "\e[34mDo you want to update?"
echo -e "\e[34m#########################################################"
read -p "Yes(y)/No(n) " -n 1 -r update
if [[ $update =~ ^[Yy]$ ]]
then
echo -e "\e[32m#########################################################"
echo -e "\e[32mI am updating myself..."
echo -e "\e[32m#########################################################"
sleep 4
curl --silent "$bashlyurl" > bashlyblog.sh
curl --silent "$templateurl" > template.html
echo -e "\e[32m#########################################################"
echo -e "\e[32mUpdate done. Restart..."
echo -e "\e[32m#########################################################"
/bin/bash bashlyblog.sh
exit 1
fi
fi
You might be typing the letter y and pressing Enter key whereas your script moves on as soon as you've typed y, since you added -n 1 to your read command.
Try typing y without pressing Enter key, or removing -n 1 if you'd rather press key Enter.

BASH - curl command not work into loop with for

i need check status of some link listen in a file called paths.txt, i have write a simple for loop but not work
for LINK in $(cat paths.txt)
do
CURL="$(curl -I $LINK 2>/dev/null | head -n 1 | cut -d$' ' -f2)"
if [ "${CURL}" = "200" ]
then
echo ${LINK} >> true.txt
else
echo ${LINK} >> false.txt
fi
done
If i launch the curl command from terminal i read the right status, instead if i make an echo of CURL variable i not have any output
Run the script like this: bash -x myscript and watch the executed commands.
don't use cat in bash scripts, because is bad practice and can be problems with big files.
SCRIPTDIR=`dirname -- "$0"`
for siteUrl in $( < "$SCRIPTDIR/paths.txt")
do
if [[ -z "$siteUrl" ]]; then break; fi
if [[ "$(curl --write-out "%{http_code}\n" --silent --output /dev/null ${siteUrl} )" = "200" ]]; then
echo ${siteUrl} >> true.txt
else
echo ${siteUrl} >> false.txt
fi
done

Bash Loop and exit status check

An array holds the files accessed, and the archive files are split into smaller sizes in preparation for online backup. I am attempting to retrieve the exit code for each iteration through the loop of the split command. However, it is returning Exit Code 1, yet it says that the operation was successful. Why?
#!/bin/bash
declare -a SplitDirs
declare -a CFiles
CDIR=/mnt/Net_Pics/Working/Compressed/
SDIR=/mnt/Net_Pics/Working/Split/
Err=/mnt/Net_Pics/Working
SplitDirs=(`ls -l "$CDIR" --time-style="long-iso" | egrep '^d' | awk '{print $8}'`)
for dir in "${SplitDirs[#]}"
do
if [ ! -d "$SDIR""$dir" ]; then
mkdir "$SDIR""$dir"
else continue
fi
CFiles=(`ls -l "$CDIR$dir" --time-style="long-iso" | awk '{print $8}'`)
for f in "${CFiles[#]}"
do
if [ ! -e "$SDIR""$dir"/"$f" ]; then
split -d -a 4 -b 1992295 "$CDIR""$dir"/"$f" "$SDIR""$dir"/"$f" --verbose
if [[ "$?" == 1 ]]
then
rm -rf "$SDIR""$dir" && echo "$SDIR""$dir" "Removed due to Error code" "$?""." "Testing Archives and Retrying..." 2>&1 | tee "$Err"/Split_Err.log
7z t "$CDIR""$dir"/"$f" >> tee stdout.log 2>> "$Err"/"$dir"/7z_Err.log >&2
mkdir "$SDIR""$dir" && split -d -a 4 -b 1992295 "$CDIR""$dir"/"$f" "$SDIR""$dir"/"$f" --verbose
if [[ "$?" == 1 ]]
then
rm -rf "$SDIR""$dir" && echo "$SDIR""$dir" "Removed a second time due to Error code "$?". Skipping..." 2>&1 | tee "$Err"/Split_Err.log
continue
else
echo "Split Success:" "$SDIR""$dir"/"$f" "ended with Exit status" "$?" && continue
fi
else
echo "Split Success:" "$SDIR""$dir" "ended with Exit status" "$?" && continue
fi
else
echo "$SDIR""$dir"/"$f" "Exists... Skipping Operation" 2>&1 | tee "$Err"/"$dir"/Split_Err.log
continue
fi
done
(The echo piping in a previous revision of the question was misplaced code, and thank you for pointing that out. The exit code remains the same, though. Overall,the script does what I want it to except for the exit code portion.)
Remove | echo $?. you are processing the return code of echo command(last command).

Bash remote files system directory test

the more I learn bash the more questions I have, and the more I understand why very few people do bash. Easy is something else, but I like it.
I have managed to figure out how to test directories and there writablity, but have a problem the minute I try to do this with a remote server over ssh. The first instance testing the /tmp directory works fine, but when the second part is called, I get line 0: [: missing]'`
Now if I replace the \" with a single quote, it works, but I thought that single quotes turn of variable referencing ?? Can someone explain this to me please ? Assuming that the tmp directory does exist and is writable, here the script so far
#!/bin/bash
SshHost="hostname"
SshRsa="~/.ssh/id_rsa"
SshUser="user"
SshPort="22"
Base="/tmp"
Sub="one space/another space"
BaseBashExist="bash -c \"[ -d \"$Base\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseExist=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseBashExist} )
echo -n $Base
if [ $? -eq 0 ]
then
echo -n "...OK..."
else
echo "...FAIL"
exit 1
fi
BaseBashPerm="bash -c \"[ -w \"$Base\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseExist=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseBashPerm} )
if [ $? -eq 0 ]
then
echo "...writeable"
else
echo "...not writeable"
fi
BaseAndSub="$Base/$Sub"
BaseAndSubBashExist="bash -c \"[ -d \"$BaseAndSub\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseAndSubExist=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseAndSubBashExist} )
echo -n $BaseAndSub
if [ $? -eq 0 ]
then
echo -n "...OK..."
else
echo "...FAIL"
exit 1
fi
BaseAndSubBashPerm="bash -c \"[ -w \"$BaseAndSub\" ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHBaseAndSubPerm=$( ssh -l $SshUser -i $SshRsa -p $SshPort $SshHost ${BaseAndSubBashPerm} )
if [ $? -eq 0 ]
then
echo -n "...writeable"
else
echo "...not writeable"
fi
exit 0
The first thing you should do is refactor your code with simplicity in mind, then the quoting error will go away as well. Try:
if ssh [flags] test -w "'$file'"; then
Encapsulate your SSH flags in a ssh config to facilitate re-use, and your script will shorten dramatically.
You are fine with single quotes in this context; by the time the script is seen by the remote bash, your local bash has already substituted in the variables you want to substitute.
However, your script is a total mess. You should put the repetitive code in functions if you cannot drastically simplify it.
#!/bin/bash
remote () {
# most of the parameters here are at their default values;
# why do you feel you need to specify them?
#ssh -l "user" -i ~/.ssh/id_rsa -p 22 hostname "$#"
ssh hostname "$#"
# —---------^
# if you really actually need to wrap the remote
# commands in bash -c "..." then add that here
}
exists_and_writable () {
echo -n "$1"
if remote test -d "$1"; then
echo -n "...OK..."
else
echo "...FAIL"
exit 1
fi
if remote test -w "$1"; then
echo "...writeable"
else
echo "...not writeable"
fi
}
Base="/tmp"
# Note the need for additional quoting here
Sub="one\\ space/another\\ space"
exists_and_writable "$Base"
BaseAndSub="$Base/$Sub"
exist_and_writable "$BaseAndSub"
exit 0
ssh -qnx "useraccount#hostname"
"test -f ${file absolute path} ||
echo ${file absolute path} no such file or directory"

Resources