Script in crontab to be executed only if is equal or exceeds a value - linux

I currently have a script in crontab for rsync (and some other small stuff). Right now the script is executed every 5 minutes. I modified the script to look for a specific line from the rsync part (example from my machine, not the actual code):
#!/bin/bash
Number=`/usr/bin/rsync -n --stats -avz -e ssh 1/ root#127.0.0.1 | grep "Number of regular files transferred" | cut -d':' -f 2 | tr -d 040\054\012`
echo $Number
Let's say the number is 10. If the number is 10 or below I want the script executed through the crontab. But if the number is bigger I want to be executed ONLY manually.
Any ides?

Maybe you can use an argument to execute it manually, for example:
if [[ $Number -le 10 || $1 == true ]];then
echo "executing script..."
fi
This will execute if $Number is less or equal to 10 or if you execute it with true as the first positional argument, so if $Number is greater than 10 it won't execute in your crontab and you can execute your script manually with ./your_script true.

Related

Script to check if vim is open or another script is running?

I'm making a background script that requires a user to input a certain string (a function) to continue. The script runs fine, but will interrupt anything else that is open in vim or any script that is running. Is there a way I can test in my script if the command line is waiting for input to avoid interrupting something?
I'm running the script enclosed in parenthesis to hide the job completion message, so I'm using (. nightFall &)
Here is the script so far:
#!/bin/bash
# nightFall
clear
text=""
echo "Night begins to fall... Now might be a good time to rest."
while [[ "$text" != "rest" ]]
do
read -p "" text
done
Thank you in advance!
If you launch nightFall from the shell you are monitoring, you can use "ps" with the parent PID to see how many processes are launched by the shell as well:
# bg.sh
for k in `seq 1 15`; do
N=$(ps -ef | grep -sw $PPID | grep -v $$ | wc -l)
(( N -= 2 ))
[ "$N" -eq 0 ] && echo "At prompt"
[ "$N" -ne 0 ] && echo "Child processes: $N"
sleep 1
done
Note that I subtract 2 from N: one for the shell process itself and one for the bg.sh script. The remainder is = how many other child processes does the shell have.
Launch the above script from a shell in background:
bash bg.sh &
Then start any command (for example "sleep 15") and it will detect if you are at the prompt or in a command.

Deleting an existing job/task in Crontab [duplicate]

This question already has answers here:
Use sed to edit crontab
(2 answers)
Closed 3 years ago.
I'm writing a script and I'm wanting to be able to delete a specific job/task that a user can create using the Crontab command.
I know that to be able to simply delete all jobs/tasks, you just use:
crontab -r;
But if there's multiple jobs/tasks how are you able to list them and then delete selected ones?
Use crontab -e, it should open all the cron tasks in the system editor and then you remove the specific entry and save and exit. Cheers
Edit: Adding remove from script
You can do something like -
crontab -l | grep -v '<SPECIFICS OF YOUR SCRIPT HERE>' | crontab -
from your script. Give it a try and let me know if it worked
Display available jobs with indexing,
read user choice,
delete job by its index
#!/usr/bin/env bash
# Array of cron job entries
typeset -a cron_entries
# Store the contab jobs into an array
mapfile -t cron_entries < <(crontab -l | grep -vE '^(#.*|[[:space:]]*)$')
if (( ${#cron_entries[#]} > 0 )); then
# List all the jobs
echo "Here are the current cron jobs:"
printf 'Index\tJob entry\n'
for ((i=0; i<"${#cron_entries[#]}"; i++)); do
printf '%4d\t%s\n' $i "${cron_entries[i]}"
done
# Prompt user for job index or exit
read -p $'\nPlease choose a job index to delete, or an invalid index to abandon: ' -r answer
# If answer is a positive integer and within array bounds
if [[ "$answer" =~ ^[0-9]+$ ]] && (( answer < ${#cron_entries[#]} )); then
# Show deleted entry
printf '\nDaleting:\t%4d\t%s\n' "$answer" "${cron_entries[answer]}"
# Delete the selected cron entry
unset cron_entries["$answer"]
# Send the edited cron entries back to crontab
printf '%s\n' "${cron_entries[#]}" | crontab -
else
printf '\nAborted with choice %q\nNo job deleted\n' "$answer"
fi
else
printf 'There is no cron job for user: %s\n' "$USER"
fi

clear my script logs every 10 second

I have script with name : run.sh
This is my script code :
#!/usr/bin/env bash
install() {
sudo apt-get update
sudo apt-get upgrade
}
if [ "$1" = "install" ]; then
install
else
if [ ! -f ./tg/tgcli ]; then
echo "tg not found"
echo "Run $0 install"
exit 1
fi
#sudo service redis-server restart
#./tg/tgcli -s ./bot/bot.lua -l 1 -E $#
./tg/tgcli -s ./bot/bot.lua $#
fi
and when run this script give me output like this every second :
[09:54] 2014 Hello
[09:55] 2014 Hi
[09:57] 2014 How Are you ?
and many like this (thousands in hour !)
and my server get slow in 5 hour.
i check print commands in bot.lua but there are no way to remove print it.
can you add some codes to clear my script logs every 10 second ?
Thanks a lot.
My Script Output Doesn't Save Anywhere and Just Show me in terminal
I want a code such as clear command on linux terminal , clear my script logs every 10 minute or 5 minute.
After 5 day of script running i can (sometimes can't) login my server and my server get very slow and i must wait 3 or 5 minute to login my server and this amazing after login my server my server again get fast !
and i forgot say i use byobu screen for run my scripts and I think screen get my server slow down.
I don't think that something as simple as this would cause your server to slow down, but you can add a check to your script to calculate the size or line count of your log file every time it runs.
This function assumes you are redirecting your output to a log file. Set the variables to whatever makes the most sense.
log_check() {
line_count=$(wc -l $log_file | awk '{print $1}')
size_check=$(du -ax $log_file | awk '{print $1}')
max_file_size="1500"
max_file_length="1000"
if [[ $line_count >= $max_file_length || $size_check >= $max_file_size ]]; then
echo "" > $log_file
fi
}
I would also recommend using [[ ]] over [ ] since this is a bash script, as long as you don't plan in it being posix compliant and only plan on using it with bash [[]] is always better than [].
EDIT:
Since you are logging output to the terminal and not a file you can literally use the clear command in your script.
Try this out and see how the functionality works
for i in {1..20}; do
echo $i
if (( i == 10 )); then
clear
fi
done
I'm assuming your code has a loop somewhere, if not it will be a bit more complex to clear the terminal session. I'm not really sure what part of your code is actually printing anything to stdout, I'm guessing it's this piece here
./tg/tgcli -s ./bot/bot.lua $#
You could try something like this, which will background your initial process and then run clear every 60 seconds to clear the terminal window. Is there any reason you're not writing the output to a log file? That alone could solve some of your issues as well.
#!/bin/bash
./tg/tgcli -s ./bot/bot.lua $# &
pid="$!"
check_pid() {
ps -ef |grep "$pid"|grep -v 'grep' &>/dev/null
}
cnt=1
until ! check_pid; do
if (( cnt == 6 )); then
clear
cnt=1
fi
sleep 10
((cnt++))
done

Bash scripting wanting to find a size of a directory and if size is greater than x then do a task

I have put the following together with a couple of other articles but it does not seem to be working. What I am trying to do eventually do is for it to check the directory size and then if the directory has new content above a certain total size it will then let me know.
#!/bin/bash
file=private/videos/tv
minimumsize=2
actualsize=$(du -m "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
echo "nothing here to see"
else
echo "time to sync"
fi
this is the output:
./sync.sh: line 5: [: too many arguments
time to sync
I am new to bash scripting so thank you in advance.
The error:
[: too many arguments
seems to indicate that either $actualsize or $minimumsize is expanding to more than one argument.
Change your script as follows:
#!/bin/bash
set -x # Add this line.
file=private/videos/tv
minimumsize=2
actualsize=$(du -m "$file" | cut -f 1)
echo "[$actualsize] [$minimumsize]" # Add this line.
if [ $actualsize -ge $minimumsize ]; then
echo "nothing here to see"
else
echo "time to sync"
fi
The set -x will echo commands before attempting to execute them, something which assists greatly with debugging.
The echo "[$actualsize] [$minimumsize]" will assist in trying to establish whether these variables are badly formatted or not, before the attempted comparison.
If you do that, you'll no doubt find that some arguments will result in a lot of output from the du -m command since it descends into subdirectories and gives you multiple lines of output.
If you want a single line of output for all the subdirectories aggregated, you have to use the -s flag as well:
actualsize=$(du -ms "$file" | cut -f 1)
If instead you don't want any of the subdirectories taken into account, you can take a slightly different approach, limiting the depth to one and tallying up all the sizes:
actualsize=$(find . -maxdepth 1 -type f -print0 | xargs -0 ls -al | awk '{s += $6} END {print int(s/1024/1024)}')

Basic bash shell scripting on nmon

I'm having a problem trying to run nmon using my own script where nmon is deployed in the linux environment.
Based on this script, I am required to execute command "test.sh 2 5", with variables represented by value 2 and 5
#!/bin/bash
#sh test.sh variable1 variable2
./nmon -f -s$1 -c $2
total=$(( $1 * $2 ))
echo "------------------------------------------------"
echo -e "Providing $2 snapshots with interval of $1s"
echo -e "Saving into $HOSTNAME. Completing in $total seconds\n\n"
However, I am receiving the following output:
[osmusr#bssosmappv4001 ~]$ sh nmonscript2.sh 2 4
------------------------------------------------
Providing 4 snapshots with interval of 2s
secondsnto bssosmappv4001. Completing in 8
May I know which part did I missed out? Why is it not displaying the output correctly?
total has a carriage return (0x0D/\r/^M) after it. Most likely the script has windows line endings (\r\n), and the \r is getting tacked onto the total assignment. Run the file through dos2unix.

Resources