Hello I want to create a script that shutdowns Linux after a certain time (e.g 15 seconds) with a countdown displayed in the terminal (Linux is shutting down after 15s.). It has to be with while.
You can use the following :
#!/bin/bash
COUNTER=15
while [ 1 ]
do
if [ ${COUNTER} -eq 0 ]
then
break
fi
echo "Linux is shutting down after ${COUNTER}s."
sleep 1
COUNTER=$( echo "${COUNTER}-1" | bc )
done
sudo poweroff
If you really want to display the counter on the screen, this would work:
#!/bin/bash
seconds=15
echo "Linux is shutting down after ${seconds}s"
date_1=$((`date +%s` + $seconds))
while [ "$date_1" -ge `date +%s` ]; do
echo -ne "$(date -u --date #$(($date_1 - `date +%s` )) +%H:%M:%S)\r"
done
echo -e "Do you really want to shutdown the system? Press [Y/y] to shutdown or [n/N] to cancel/exit:"
read var
if [[ "$var" == "y" ]] || [[ "$var" == "Y" ]]
then
sudo poweroff
elif [[ "$var" == "n" ]] || [[ "$var" == "N" ]]
then
exit 1
fi
Basically, it'll accept [Y/y] from the user to shutdown and [n/N] to exit.
Related
I have a pretty simple bash script that coordinates running a couple python scripts. What I am having trouble figuring out is why after running the bash script (. bash_script.sh), the terminal hangs. I can't ctrl+c, ctrl+z or do anything except restart the SSH session. All I see is just a blinking cursor. Checking all the log files indicates a 0 status exit code with no errors in the scripts themselves. Running ps aux | grep bash_script.sh does not show any anything running either. Is there anyway to debug this?
#!/bin/bash
exec >> <DIR>/logfile.log 2>&1
script_message () {
status_arg=$1
if [[ $status_arg = "pass" ]]; then
printf "Script Done\n"
printf '=%.0s' {1..50}
printf "\n"
elif [[ $status_arg = "fail" ]]; then
printf "Script Failed\n"
printf '=%.0s' {1..50}
printf "\n"
else
:
fi
}
current_date=$(date '+%Y-%m-%d %H:%M:%S')
day=$(date +%u)
hour=$(date +%H)
printf "RUN DATE: $current_date\n"
# activate virtual env
source /<VENV DIR/bin/activate>
python <PYTHON SCRIPT>.py >> <DIR>/logfile2.log 2>&1
retVal=$?
if [[ $retVal -eq 0 && $day -eq 4 ]]; then
python <PYTHON SCRIPT 2>.py >> <DIR>/logfile3.log 2>&1
script_message pass
elif [[ $retVal -eq 0 ]]; then
script_message pass
else
#:
script_message fail
fi
echo $?
PROMPT_COMAND runs slow. Code optimization needed.
I use bash builtin PROMPT_COMMAND to customize PS1. Too much echo | grep commands were executed to get colorful git branch indication.The prompt runs much slower. Any ideas about optimazation?
function git_branch {
branch="`git branch 2>/dev/null | grep "^\*" | sed -e "s/^\*\ //"`"
if [ "${branch}" != "" ];then
if [ "${branch}" = "(no branch)" ];then
branch="(`git rev-parse --short HEAD`...)"
fi
echo "$branch"
fi
}
# display last two dentry
function get_curdir {
dir=$(pwd);
last_dirent=${dir##*/}
dir=${dir%/*}
lastbutone_dirent=${dir##*/}
echo -n "${lastbutone_dirent}/${last_dirent}"
}
# colours
RED="\[\033[1;31m\]"
GREEN="\[\033[1;32m\]"
BROWN="\[\033[0;33m\]"
BLUE="\[\033[1;34m\]"
PURPLE="\[\033[1;35m\]"
CYAN="\[\033[1;36m\]"
GRAY="\[\033[0;37m\]"
LIGHT_RED="\[\033[0;31m\]"
LIGHT_GREEN="\[\033[1;32m\]"
LIGHT_BLUE="\[\033[0;34m\]"
YELLOW="\[\033[1;33m\]"
LIGHT_PURPLE="\[\033[1;35m\]"
LIGHT_CYAN="\[\033[1;36m\]"
LIGHT_GRAY="\[\033[0;37m\]"
WHITE="\[\033[1;37m\]"
RESTORE="\[\033[0m\]" #0m restores to the terminal's default colour
function prompt_command {
RET=$?
PS1="${CYAN}[${RESTORE}${GREEN}\u${RESTORE} "
PS1+="${BLUE}$(get_curdir)${RESTORE}${CYAN}]${RESTORE}"
BRANCH=$(git_branch)
if [ "${BRANCH}" != "" ]; then
STATUS="$(git status -s 2>/dev/null)"
if echo "${STATUS}" | grep -e "??"; then
PARENTHESES_COLOR=${RED}
else
PARENTHESES_COLOR=${GREEN}
fi >/dev/null
if [ "${STATUS}" = "" ]; then
BRANCH_COLOR=${GREEN}
else
if echo "${STATUS}" | grep -e "^[ M]M"; then
if echo "${STATUS}" | grep -e "^M[ M]"; then
BRANCH_COLOR=${PURPLE}
else
BRANCH_COLOR=${RED}
fi
elif echo "${STATUS}" | grep -e "^M "; then
BRANCH_COLOR=${YELLOW}
fi
fi >/dev/null
PS1+="${PARENTHESES_COLOR}(${RESTORE}${BRANCH_COLOR}$(git_branch)${RESTORE}${PARENTHESES_COLOR})${RESTORE}"
fi
if [ "$RET" = "0" ]; then
PS1+=" ${CYAN}->${RESTORE} "
else
PS1+=" ${RED}->${RESTORE} "
fi
}
export PROMPT_COMMAND=prompt_command
update
I run a simple test in some dir where a git repo resides and use time to get time cost.
for ((i=0;i<10000;i++));do
prompt_command;
done
Performance of the original version above is:
real 3m4.567s
user 1m32.698s
sys 3m2.495s
Then I change [] to [[ ]], diff like this:
17,18c17,18
< if [ "${branch}" != "" ];then
< if [ "${branch}" = "(no branch)" ];then
---
> if [[ "${branch}" != "" ]];then
> if [[ "${branch}" == "(no branch)" ]];then
58c58
< if [ "${BRANCH}" != "" ]; then
---
> if [[ "${BRANCH}" != "" ]]; then
65c65
< if [ "${STATUS}" = "" ]; then
---
> if [[ "${STATUS}" == "" ]]; then
81c81
< if [ "$RET" = "0" ]; then
---
> if [[ "$RET" == "0" ]]; then
Performance get a little worse
real 3m7.690s
user 1m30.717s
sys 3m6.676s
So, [] doesn't matter.
But builtin regex helps a lot.
When I changes to the following and replace $(pwd) with $PWD
if [ "${BRANCH}" != "" ]; then
regex_untracked=".*^\?\?.*"
regex_staged=".*^M[ M].*"
regex_modified=".*^[ M]M.*"
STATUS="$(git status -s 2>/dev/null)"
if [[ ${STATUS} =~ $regex_untracked ]]; then
PARENTHESES_COLOR=${RED}
else
PARENTHESES_COLOR=${GREEN}
fi >/dev/null
if [[ ${STATUS} =~ $regex_modified ]]; then
if [[ ${STATUS} =~ $regex_staged ]]; then
BRANCH_COLOR=${PURPLE}
else
BRANCH_COLOR=${RED}
fi
elif [[ ${STATUS} =~ $regex_staged ]]; then
BRANCH_COLOR=${YELLOW}
else
BRANCH_COLOR=${GREEN}
fi >/dev/null
PS1+="${PARENTHESES_COLOR}(${RESTORE}${BRANCH_COLOR}$(git_branch)${RESTORE}${PARENTHESES_COLOR})${RESTORE}"
fi
Time consumed decreases:
real 2m15.534s
user 1m1.036s
sys 2m15.043s
By the way, without this colorful branch feature, performance is
real 1m0.478s
user 0m29.499s
sys 1m1.411s
bash has its own built-in regular expression matching. For example, replace
echo "${STATUS}" | grep -e "^[ M]M"
with
regex="^[ M]M"
[[ $STATUS =~ $regex ]]
so I found a script online and found it pretty suitable to my needs. basically it edits the file nitrogen places it's saved wallpaper in to another picture, so I can change the wallpaper periodically with a cron job.
#!/bin/bash
WPDIR="$HOME/Wallpapers"
random=true
apply=true
wpfile=""
function usage {
if [ $1 -eq 1 ]; then
stream=2
exitcode=255
else
stream=1
exitcode=0
fi
echo "Usage: $(basename $0) [-n|--noapply] [-h|--help] [wallpaper_location]" >&$stream
echo "If wallpaper location is not given a random wallpaper from $WPDIR will be chosen" >&$stream
exit $exitcode
}
# handle arguments
while [ $# -gt 0 ]; do
if [ "$1" = "--help" -o "$1" == "-h" ]; then
usage 0
elif [ "$1" = "--noapply" -o "$1" = "-n" ]; then
apply=false
else
if ! $random; then
usage 1
elif [ ! -f "$1" ]; then
echo "file '$1' not found" >&2
exit 1
fi
random=false
{ cd $(dirname "$1"); dir=$(pwd); }
wpfile="$dir/$(basename "$1")"
fi
shift
done
if $random; then
wpfile=$(ls "$WPDIR"/*.jpg | sort -R | head -n 1)
echo "chose $wpfile" >&2
fi
cat >$HOME/.config/nitrogen/bg-saved.cfg <<EOF
[:0.0]
file=$wpfile
mode=4
bgcolor=# 0 0 0
EOF
if $apply; then
nitrogen --restore
fi
my problem is the scaling of the pictures. I can't set it to auto-fill this way.
I'm bad, I should feel bad. When writing to >$HOME/.config/nitrogen/bg-saved.cfg , the mode is set. this mode is literally the mode nitrogen provides. Try a bit around with nitrogen and look what mode is set in the file. zoomed-fill = 5, for my example.
I have a flaky Internet connection, so I decided to make a bash script that would alert me whenever the internet is back. This is the script:
#!/bin/bash
# set -x
while [ 1 ];do
STATUS_CURRENT=$(ping -q -w 1 -c 1 google.com > /dev/null && echo connected || echo disconnected)
if [[ $STATUS_CURRENT == "connected" && $STATUS_LAST != "connected" ]];then
aplay /home/user/bin/online.wav
notify-send "We've connected"
elif [[ $STATUS_CURRENT == "disconnected" && $STATUS_LAST == "connected" ]];then
aplay /home/user/bin/offline.wav
notify-send "Disconnected now"
fi
STATUS_LAST=$STATUS_CURRENT
sleep 2
done
I have this added in /etc/rc.local to have it executed on startup. The problem with this script is that it sometimes fail. Even when there's Internet connectivity, the script sends notification saying it's disconnected (immediately followed by the "connected" message).
How can I avoid this problem? Does it have something to do with the fact that ping is slow to fail? How can the script be improved?
With "netcat" it works very stable for me
#!/bin/bash
status=0
do_on=("/home/user/bin/online.wav"
"We've connected")
do_off=("/home/user/bin/offline.wav"
"Disconnected now")
while [ 1 ] ;do
nc -zw 2 google.de 80
ret="$?"
if [ "$ret" = 0 -a "$status" = 0 ] ;then
aplay ${do_on[0]}
notify-send ${do_on[1]}
status=1
elif [ "$ret" -ne 0 -a "$status" = 1 ] ;then
aplay ${do_off[0]}
notify-send ${do_off[1]}
status=0 ;fi
sleep 2 ;done
You should test your DNS server in advance
cheers Karim
Ok, stupid newbie question here. I thought I was making a countdown timer. This is supposed to count down from 5 and once it is at 0 then execute the echo "time is up clown" then end. What am I doing wrong here?
seconds=5
date1=$((`date +%s` + $seconds));
while [ "$date1" -ne `date +%s` ]; do
if (!$date1 -lt ((`date +%s` + $seconds)+1)); then
echo "time is up clown";
break;
fi;
echo -ne "$(date -u --date #$(($date1 - `date +%s` )) +%H:%M:%S)\r";
done
#!/bin/bash
SECS=5
while [[ 0 -ne $SECS ]]; do
echo "$SECS.."
sleep 1
SECS=$[$SECS-1]
done
echo "Time is up, clown."