I have a linux server running, which I back up every day.
The backup script works like a charm, but I would like some feedback on completion with or without errors.
#!/bin/bash
# Hier gaan we zoeken naar alle mappen en onderliggende mappen in de LinuxKJ server.
find /var/www -maxdepth 1 -mindepth 1 -print0 | while read -d $'\0' foldername
do
# Hier gaan we alle mappen in zipjes comprimeren en overzetten naar een andere locatie. Overigens laat hij _Inactief eruit.
fatsoenlijkPad=$(echo $foldername)
tar --exclude='/var/www/_Inactief' -zcvpf /mediabak/winboxbak/"${fatsoenlijkPad##*/}".tar.gz "$fatsoenlijkPad"
# Hier gaan we kijken of de functie hierboven een succes return (Succes = 0) (Fout = 1,2,3,4, etc)
if ( $? == 0 ) then
Mailtext=$(echo "Backup succesvol.")
else
Mailtext=$(echo "Backup failed.")
fi
done
# Hier gaan we mailen wat de functie heeft gereturned
mail -s "Linux backup" "example#example.com"
$Mailtext
./backupscript.sh: line 9: 141: command not found
Can anyone help me to fix this issue?
In bash square brackets are used. Hence change
if ( $? == 0 ) then
to
if [ $? == 0 ]; then
Edit: Change
mail -s "Linux backup" "example#example.com"
$Mailtext
to
echo $Mailtext | mail -s "Linux backup" example#example.com
To verify that your are able to send and receive a mail, try to send a mail with dummy text as below.
echo "Testing Mail" | mail -s "Linux backup" example#example.com
As commented, your variable assignement for Mailtext are inefficient (it works, but it has no sense to use an echo command to assign a text value).
As for your email sending, your mail command invocation should be :
echo $Mailtext | mail -s "Linux backup" "example#example.com"
Related
I have this script that checks if the dcos auth login works, but the file i am redirecting the output to is always zero size, when i run the script from bash shell the file is greater than zero . what am i doing wrong ?? , the two functions i use below:
try_to_login()
{
# first needs to be logged as skyusr
# try to login and log the result to tmp file
# Sometimes the file is empty so we try again to login
# if the second time is OK it jumps to check the output
cd /home/skyusr/scripts/
dcos auth login --username=admin --password=admin > /home/skyusr/scripts/tmp.sal
}
check_login_result()
{
# Checks if the output of the login is "Login Successful!"
# If YES then writes to log file, if not sends mail and writes to log.
#export mail_to="salim.bisharat#amdocs.com,anis.faraj#amdocs.com"
export mail_to="salim.bisharat#amdocs.com"
now=$(date)
text_to_check=$(cat /home/skyusr/scripts/tmp.sal)
if [ -s /home/skyusr/scripts/tmp.sal ]
then
if [ "$text_to_check" = "Login successful!" ]
then
echo "$now - Check Successful" >> /home/skyusr/scripts/logs/login_log.log
else
cat /home/skyusr/scripts/logs/mail_temp.log | mailx -s "!!! CRITITCAL -- Check DCOS login !!!" $mail_to
echo "$now - !! ERROR ! Sent mail !! " >> /home/skyusr/scripts/logs/login_log.log
fi
fi
}
In this script you define, but you do not call the functions. Simply append function calls:
# ...
echo "$now - !! ERROR ! Sent mail !! " >> /home/skyusr/scripts/logs/login_log.log
fi
fi
} # ... the last line of your script here
try_to_login # calls here ...
check_login_result
Can someone help and tell me why this isn't working?
I have checked the script and solved some problems but it still doesn't works fine and I can't find the mistake.
#!/bin/bash
#variabelen
IP="192.168.0."
array=($#)
#functies
What's wrong with the array? My linux told me that there is a syntax error on line 12 so with that array but he doesn't tell me what.
function Sorteer(){
array=($(printf '%s\n' "$#"|sort -nu))
for i in ${array[#]};do
ping -c -1 "IP"$i
done
}
function Telbij(){
# given number $i +200
b=$(( $i + 200 ))
if (( b > 255 ))
then
echo "Neem kleiner getal";
else
ping -c 1 "IP"$b;
fi
}
function XXYY() {
#ping 65-68 = ping 65 66 67 68
start=${1%-*}
end=${1#*-}
for ((i=start;i<=end;i++));do
ping -c 1 "$IP"$i
done
}
The mistake is in the if else function: http://prntscr.com/7gr8yf
But I don't know what that means: "The mentioned parser error was in this else clause."
if [ "$#" -eq 0 ]; then
echo "Er moet minimaal 1 parameter worden meegegeven "
exit 0
else
case
-h -help ) echo "Geef de laatste cijfers van het IP-adres van de pc's om te testen.";;
XX-YY ) XXYY;;
-t ) Telbij;;
- sort ) Sorteer;;
esac
fi
done
Don't know what's specifically not working but,
in Sorteer function you should double quote array expansions to avoid re-splitting elements.
Try change to following:
function Sorteer(){
array=($(printf '%s\n' "$#"|sort -nu))
for i in "${array[#]}";do
ping -c -1 "IP"$i
done
}
Now your case operator should be like:
case $some_value in
-help ) echo "Geef de laatste cijfers van het IP-adres van de pc's om te testen.";;
XX-YY ) XXYY;;
-t ) Telbij;;
-sort ) Sorteer;;
esac
This will fix your if issue as well
Basically I have to make my linux program do the same thing as my MS-DOS. Could someone help with pointers and things like that?
All the program currently does, is pull a menu for basic, advanced account creation and close.
Advanced has nothing in atm, and close does what you expect. Basic then asks you for:
Full name
Username
Password
It then saves it all in a .log file (after checking for usernames already entered) along with the exact time of creation. For example:
Badja
John Doe
123
23/04/2015 15:07:32.61
#echo off
c:
:1
set curdir=%test%
echo Welcome to OP-SYS Account creation. Please choose which mode you would like to continue in.
echo.
echo [1] Basic Account Creation
echo [2] Advanced Account Creation
echo [3] Exit
echo.
REM Menu choices
set /p cat=
if %cat%==1 (
goto 2
) else if %cat%==2 (
goto 3
) else if %cat%==3 (
goto 5
) else (
goto 4
)
:2
REM Basic account creation
echo Welcome to basic account creation.
REM user enters details
REM Username
echo Please Enter a Username
set /p username=
echo.
REM Real Name
echo Please enter your full name
set /p fullname=
echo.
REM Password
echo Please enter a password
set /p password=
echo.
REM Real name
REM Save to file
if exist %username%.log (
echo User name already exists, please enter a new user name to create an account, or return to the log in screen
goto 1
) else (
echo %username% >> %username%.log
echo %fullname% >> %username%.log
echo %password% >> %username%.log
echo %date% %time% >> %username%.log )
timeout /t 3 /nobreak > NUL
REM pause
goto end
:3
REM Advanced account creation
echo Welcome to advanced account creation.
echo This is not complete, please return to main menu.
Pause
goto 1
:4
REM Error
echo error
echo.
goto 1
:5
REM Exit
echo Goodbye.
goto end
:end
exit
I know there are a few things that can't be copied over to linux, but I just don't know where to start, this is my basis:
PS3='Please enter your choice: '
options=("cat 1" "cat 2" "end")
select opt in "${options[#]}"
do
case $opt in
"cat 1")
echo "Basic"
;;
"cat 2")
echo "Advanced"
;;
"end")
break
;;
*) echo invalid option;;
esac
done
Any help would be amazing guys!
function choice1 {
echo "Do stuff here to create an account"
}
function choice2 {
echo "Get the point?"
}
function choice3 {
exit
}
#### Main
echo "Welcome to OP-SYS Account creation. Please choose which mode you would like to continue in."
echo
echo "[1] Basic Account Creation
[2] Advanced Account Creation
[3] Exit"
echo
read CHOICE #### This loads your choice into a variable
eval choice"$CHOICE" ### This is evaluation awesomeness
If the eval seems strange, you can go with a more traditional case...esac statement to call the various functions. I would suggest getting your menu cycling and escaping the way that you want before adding in your special function.
clear
echo "Welcome to OP-SYS Account creation. Please choose which mode you would like to continue in."
echo
echo "[1] Basic Account Creation
[2] Advanced Account Creation
[3] Exit"
echo
I have to make a phone_book in shell (bash)..
Here's what the program should do.
Add a number : You ask for the name and the number.If it doesn't exist already ( verification) then add a file in the same directory called $name and contain 1 line: the number.
Obtain the liste of names already saved.
Look for a number by giving his name ( we have to verify also if it exists or not.
modify a number ( verification also)
looking for a name by giving his number.( verification).
I Think that we have to use case I looked in the net, but I have difficulties with Shell.
Hope you helps me guys. Don't hesitate to ask me questions. Thanks
#!/bin/bash
echo " 1)Ajouter une fiche
2)Obtenir la liste des noms déjà enregistrés
3)Chercher un numéro de téléphone
4)Modifier un numero de téléphone
5)Rechercher un nom"
read x
case $x in
1)
echo " Tapez le nom à rajouter"
read nom
touch $nom
;;
UPDATE:
I have almost finished it, I have a problem with the 5) when i type an existant number , it always telling me that it doesn't exist..
Feel free to make some improvement in my code :)
#!/bin/bash
echo " 1)Ajouter une fiche
2)Obtenir la liste des noms déjà enregistrés
3)Chercher un numéro de téléphone
4)Modifier un numero de téléphone
5)Rechercher un nom"
read x
case $x in
1)
echo " Tapez le nom à rajouter"
read nom
while [ -f $nom ]; do
echo "Le fichier existe déjà"
echo " Tapez le nom à rajouter"
read nom
done
touch $nom
echo " Maintenant, tapez le numero de la personne à rajouter"
read numero
echo $numero >> $nom
;;
2)
echo $(ls);;
3)
echo " Tapez le nom de la personne que vous recherchez"
read nomrech
while [ ! -f $nomrech ]; do
echo "Le fichier n'existe pas"
read nomrech
done
cat $nomrech
;;
4)
echo "Tapez le nom d'un contacte à modifier"
read nommodif
while [ ! -f $nommodif ]; do
echo "Le fichier n'existe pas"
read nommodif
done
echo "Tapez le nouveau numéro à modifier"
read nouvnum
echo $nouvnum > $nommodif
;;
5)
echo " Tapez le numero de la personne que vous cherchez"
read numchercher
while ! grep -i "$numchercher" * ; do
echo "ce numero n'existe pas "
read nomchercher
done
grep $numchercher *
;;
esac
First of all, you need to think about how you will actually store the datas. Then, try to associate an action to each items:
Create a file named by the input containing one single line
browse the folder and extract all the filenames in that directory
find a file in a directory, given its name
modify the content of a file given its name (you can trash the content of the file at that point)
Find a filename given a pattern
So basically, I think you can manage to do the assignment with the following commands: cat, find, *, grep and that's it!
Update:
For your last question (5th point), it seems to me that your code is really complicated. Have a look on this sample:
$ echo 0123456789 > john
$ echo 0987654321 > bob
$ grep 0987654321 *
bob:0987654321
$ grep jfkljlfds *
$ echo $?
1
$ grep 0123456789 *
john:0123456789
$ echo $?
0
$ false
$ echo $?
1
$ false || echo "oops that one didn't work"
oops that one didn't work
Now I think you have everything you need to keep going.
$? is the return code from previous command. If you have a look on man grep (1):
EXIT STATUS
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling
code should check for '2' or greater.)
So basically, the trick using the or operator (||) is used to display an error only if the left part returned false.
I suppose read name; grep $name * || echo "$name was not found" would do the trick.
And by the way, you're often asking arguments twice (after checking). You shouldn't need that. The variable still exists after your test.
I created a simple linux script that essentially calls sqlplus and puts the results in variable X. I then analyze X and determine whether or not I need to send out a syslog message.
The script works perfectly when I run it from the command line as "oracle"; however when I use crontab as "oracle" and add it to my job, X isn't getting filled.
I could be wrong, but I believe the issue is since cron runs things in silent mode, X isn't actually getting filled, but when I run it manually it is.
Here's my crontab -l result (as oracle):
0,30 * * * * /scripts/isOracleUp.sh syslog
Here's my full script:
#Created by: hatguy
#Created date: May 8, 2012
#File Attributes: Must be executable by "oracle"
#Description: This script is used to determine if Oracle is up
# and running. It does a simple select on dual to check this.
DATE=`date`
USER=$(whoami)
if [ "$USER" != "oracle" ]; then
#note: $0 is the full path of whatever script is being run.
echo "You must run this as oracle. Try \"su - oracle -c $0\" instead"
exit;
fi
X=`sqlplus -s '/ as sysdba'<<eof
set serveroutput on;
set feedback off;
set linesize 1000;
select count(*) as count_col from dual;
EXIT;
eof`
#This COULD be more elegant. The issue I'm having is that I can't figure out
#which hidden characters are getting fed into X, so instead what I did was
#check the string legth (26) and checked that COUNT_COL and 1 were where I
#expected.
if [ ${#X} -eq 26 ] && [ ${X:1:10} = "COUNT_COL" ] && [ ${X:24:3} = "1" ] ; then
echo "Connected"
#log to a text file that we checked and confirmed connection
if [ "$1" == "syslog" ]; then
echo "$DATE: Connected" >> /scripts/log/isOracleUp.log
fi
else
echo "Not Connected"
echo "Details: $X"
if [ "$1" == "syslog" ]; then
echo "Sending this to syslog"
echo "==========================================================" >> /scripts/log/isOracleUp.log
echo "$DATE: Disconnected" >> /scripts/log/isOracleUp.log
echo "Message from sqlplus: $X" >> /scripts/log/isOracleUp.log
/scripts/sendMessageToSyslog.sh "PROD Oracle is DOWN!!!"
/scripts/sendMessageToSyslog.sh "PROD Details: $X"
fi
fi
Here's output when run as oracle from terminal:
Wed May 9 10:03:07 MDT 2012: Disconnected
Message from sqlplus: select count(*) as count_col from dual
*
ERROR at line 1:
ORA-01034: ORACLE not available
Process ID: 0
Session ID: 0 Serial number: 0
Here's my log output when run through oracle's crontab job:
Wed May 9 11:00:04 MDT 2012: Disconnected
Message from sqlplus:
And to syslog:
PROD Details:
PROD Oracle is DOWN!!!
Any help would be appreciated as I'm a new linux user and this is my first linux script.
Thanks!
My Oracle db skills are pretty limited but dont you need to set ORACLE_SID and ORACLE_HOME ?
Check these variables from the command lines and set these variables within cron and retry.