Grub 2, changing shift button - linux

I'm new to linux and bash, so I don't know what am I doing wrong. I set up grub to don't show, and show after pushing shift for 3 seconds. This worked fine. Then I changed line in 30_os-prober (as you can see underneath) which contained 'shift' to 'F11' as I read here: http://www.gnu.org/software/grub/manual/grub.html (13.3.33). Now when I press F11 nothing happens, and when I press shift I can see 'Grub is loading', then default OS (Ubuntu) loads without showing grub menu.
This is part of my /etc/default/grub content:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
GRUB_DEFAULT="Custom Menu"
GRUB_HIDDEN_TIMEOUT=1
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="splash"
GRUB_CMDLINE_LINUX=" splash vga=799 quiet"
and this is (IMHO) crucial part, from /etc/grub.d/30_os-prober:
adjust_timeout () {
#if [ "x${found_other_os}" = "x" ] ; then
if [ "x${GRUB_HIDDEN_TIMEOUT}" != "x" ] ; then
if [ "x${GRUB_HIDDEN_TIMEOUT_QUIET}" = "xtrue" ] ; then
verbose=
else
verbose=" --verbose"
fi
if [ "x${GRUB_HIDDEN_TIMEOUT}" = "x0" ] ; then
cat <<EOF
if [ \${timeout} != -1 ]; then
if keystatus; then
if keystatus --F11; then << There I changed shift to F11
set timeout=-1
else
set timeout=0
fi
else
if sleep$verbose --interruptible 3 ; then
set timeout=0
fi
fi
fi
EOF
else
cat << EOF
if [ \${timeout} != -1 ]; then
if sleep$verbose --interruptible ${GRUB_HIDDEN_TIMEOUT} ; then
set timeout=0
fi
fi
EOF
fi
fi
#fi
}
Thank you.

The keystatus documentation at the link you provided (and other keystatus documentation that I've come across) indicates that it accepts only --shift --ctrl or --alt as key-specific parameters. Perhaps it does not work for other keys such as F11.
The other thing to be aware of is that keystatus apparently does not work on all platforms. When that is the case, your first keystatus call will return false and the rest of the keystatus conditional logic will be skipped.

Related

Replace a part of a string in zsh

So, in my zshrc I have a blue prompt, and when the root user is used, it uses a version of the same prompt with the word blue changed to red
if [ $UID = 0 ]
then
export PS1="%B%F{red}[ %n#%m ]%f%b %F{white}:%f %F{yellow}%~%f %B%F{cyan}>%b%f "
export RPS1="%B%F{cyan}<%b%f "$(date +"%d/%m/%y ~ %H:%M:%S")""
else
export PS1="%B%F{blue}[ %n#%m ]%f%b %F{white}:%f %F{yellow}%~%f %B%F{cyan}>%b%f "
export RPS1="%B%F{cyan}<%b%f "$(date +"%d/%m/%y ~ %H:%M:%S")""
fi
I've done it like this for some time, but is it possible to just replace the word blue in PS1="%B%F{blue}..... with red? Or, the other way around?
Use a separate parameter to store you choice of color, then use that in the definition of PS1.
if [ $UID = 0 ]; then
color=red
else
color=blue
fi
PS1="%B%F{$color}[ %n#%m ]%f%b %F{white}:%f %F{yellow}%~%f %B%F{cyan}>%b%f "
RPS1="%B%F{cyan}<%b%f %D{%d/%m/%y ~ %T}" # You don't need to call date

Bash kdialog Input Box Not Clossing? Possible bad return from msgbox

I am coding in bash ,using Ubuntu 18.04, and I am playing around with kdialog. I made a simple magic eight ball themed program and I am unable to close the input box and exit the program, instead I get stuck in a loop. This code was originally made in BASH dialog and I decided to change it to kdialog. Any help would be greatly appreciated. It is something simple that I am overlooking.
#!/bin/bash
#version 3
OUTPUT="TEMP.txt"
>$OUTPUT
while [ true ]
do
shuffle() {
local i tmp size max rand
size=${#array[*]}
max=$(( 32768 / size * size ))
for ((i=size-1; i>0; i--));
do
while (( (rand=$RANDOM) >= max ));
do :;
done
rand=$(( rand % (i+1) ))
tmp=${array[i]}
array[i]=${array[rand]}
array[rand]=$tmp
done
}
array=( 'It Is Certain'
'Without A Doubt'
'Maybe'
'Signs Point To Yes'
'Most Likely'
'As I See It, Yes'
'Ask Again Later'
'Concentrate And Ask Again'
'HAHAH No..'
'Ask Again'
'Have Faith In Yourself'
'Very Doubtful'
'Outlook Not So Good'
'My Sources Say No'
'Unknown At This Time'
'Could Happen Any Moment Now'
'Is That A Joke?'
'Unlikely' )
shuffle
function sayhello(){
local n=${array[#]}-""
#display it
kdialog --msgbox "This Is What I See: ${array}"
#--clear --msgbox "${array}" 8 41
}
# show an inputbox
kdialog --title "Welcome " \
--inputbox "Ask and you shall recieve great fortune: " #8 60
function think_tank(){
progress=$(kdialog --progressbar "hmmm Let Me Think..." 4);
sleep 1;
qdbus $progress Set "" value 1 > /dev/null;
sleep 1;
qdbus $progress Set "" value 2 > /dev/null;
sleep 1;
qdbus $progress Set "" value 3 > /dev/null;
sleep 1;
qdbus $progress Set "" value 4 > /dev/null;
sleep 1;
qdbus $progress close > /dev/null;
sleep 1
#kdialog --title "This is a passive popup" --passivepopup \
#"It will disappear in about 10 seconds" 10
}
# get response
response=$?
# get data stored in $OUPUT using input redirection
name=$(<$OUTPUT)
case $response in
0)
think_tank
sayhello ${array[#]}
;;
1)
echo "Goodbye For Now."
exit 0
;;
255)
echo "Goodbye For Now."
exit 0
;;
esac
#rm $OUTPUT
done
done
After some sleep I easily figured this issue out. I removed the case statement and used if statements instead. The program would not break out of the case statement due to a return 0 from kdialog's --msgbox.
#made some quick msgbox functions
if [ "$?" = 0 ];
then
think_tank #progress bar
msg_box #results
elif [ "$?" = 1 ];
then
goodbye #closing message box
exit 0;
else
error #error message box
exit 0;
fi;

Bash prompt with the last exit code

I've been trying to customize my Bash prompt so that it will look like
[feralin#localhost ~]$ _
with colors. I managed to get constant colors (the same colors every time I see the prompt), but I want the username ('feralin') to appear red, instead of green, if the last command had a nonzero exit status. I came up with:
\e[1;33m[$(if [[ $? == 0 ]]; then echo "\e[0;31m"; else echo "\e[0;32m"; fi)\u\e[m#\e[1;34m\h \e[0;35m\W\e[1;33m]$ \e[m
However, from my observations, the $(if ...; fi) seems to be evaluated once, when the .bashrc is run, and the result is substituted forever after. This makes the name always green, even if the last exit code is nonzero (as in, echo $?). Is this what is happening? Or is it simply something else wrong with my prompt? Long question short, how do I get my prompt to use the last exit code?
As you are starting to border on a complex PS1, you might consider using PROMPT_COMMAND. With this, you set it to a function, and it will be run after each command to generate the prompt.
You could try the following in your ~/.bashrc file:
PROMPT_COMMAND=__prompt_command # Function to generate PS1 after CMDs
__prompt_command() {
local EXIT="$?" # This needs to be first
PS1=""
local RCol='\[\e[0m\]'
local Red='\[\e[0;31m\]'
local Gre='\[\e[0;32m\]'
local BYel='\[\e[1;33m\]'
local BBlu='\[\e[1;34m\]'
local Pur='\[\e[0;35m\]'
if [ $EXIT != 0 ]; then
PS1+="${Red}\u${RCol}" # Add red if exit code non 0
else
PS1+="${Gre}\u${RCol}"
fi
PS1+="${RCol}#${BBlu}\h ${Pur}\W${BYel}$ ${RCol}"
}
This should do what it sounds like you want. Take a look a my bashrc's sub file if you want to see all the things I do with my __prompt_command function.
If you don't want to use the prompt command there are two things you need to take into account:
getting the value of $? before anything else. Otherwise it'll be overridden.
escaping all the $'s in the PS1 (so it's not evaluated when you assign it)
Working example using a variable
PS1="\$(VALU="\$?" ; echo \$VALU ; date ; if [ \$VALU == 0 ]; then echo zero; else echo nonzero; fi) "
Working example without a variable
Here the if needs to be the first thing, before any command that would override the $?.
PS1="\$(if [ \$? == 0 ]; then echo zero; else echo nonzero; fi) "
Notice how the \$() is escaped so it's not executed right away, but each time PS1 is used. Also all the uses of \$?.
Compact solution:
PS1='... $(code=${?##0};echo ${code:+[error: ${code}]})'
This approach does not require PROMPT_COMMAND (apparently this can be slower sometimes) and prints [error: <code>] if the exit code is non-zero, and nothing if it's zero:
... > false
... [error: 1]> true
... >
Change the [error: ${code}] part depending on your liking, with ${code} being the non-zero code to print.
Note the use of ' to ensure the inline $() shell gets executed when PS1 is evaluated later, not when the shell is started.
As bonus, you can make it colorful in red by adding \e[01;31m in front and \e[00m after to reset:
PS1='... \e[01;31m$(code=${?##0};echo ${code:+[error: ${code}]})\e[00m'
--
How it works:
it uses bash parameter substitution
first, the ${?##0} will read the exit code $? of the previous command
the ## will remove any 0 pattern from the beginning, effectively making a 0 result an empty var (thanks #blaskovicz for the trick)
we assign this to a temporary code variable as we need to do another substitution, and they can't be nested
the ${code:+REPLACEMENT} will print the REPLACEMENT part only if the variable code is set (non-empty)
this way we can add some text and brackets around it, and reference the variable again inline: [error: ${code}]
I wanted to keep default Debian colors, print the exact code, and only print it on failure:
# Show exit status on failure.
PROMPT_COMMAND=__prompt_command
__prompt_command() {
local curr_exit="$?"
local BRed='\[\e[0;91m\]'
local RCol='\[\e[0m\]'
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u#\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
if [ "$curr_exit" != 0 ]; then
PS1="[${BRed}$curr_exit${RCol}]$PS1"
fi
}
The following provides a leading green check mark when the exit code is zero and a red cross in all other cases. The remainder is a standard colorized prompt. The printf statements can be modified to present the two states that were originally requested.
PS1='$(if [ $? -eq 0 ]; then printf "\033[01;32m""\xE2\x9C\x93"; else printf "\033[01;31m""\xE2\x9C\x95"; fi) \[\e[00;32m\]\u#\h\[\e[00;30m\]:\[\e[01;33m\]\w\[\e[01;37m\]\$ '
Why didn't I think about that myself? I found this very interesting and added this feature to my 'info-bar' project. Eyes will turn red if the last command failed.
#!/bin/bash
eyes=(O o ∘ ◦ ⍤ ⍥) en=${#eyes[#]} mouth='_'
face () { # gen random face
[[ $error -gt 0 ]] && ecolor=$RED || ecolor=$YLW
if [[ $1 ]]; then printf "${eyes[$[RANDOM%en]]}$mouth${eyes[$[RANDOM%en]]}"
else printf "$ecolor${eyes[$[RANDOM%en]]}$YLW$mouth$ecolor${eyes[$[RANDOM%en]]}$DEF"
fi
}
info () { error=$?
[[ -d .git ]] && { # If in git project folder add git status to info bar output
git_clr=('GIT' $(git -c color.ui=always status -sb)) # Colored output 4 info
git_tst=('GIT' $(git status -sb)) # Simple output 4 test
}
printf -v line "%${COLUMNS}s" # Set border length
date=$(printf "%(%a %d %b %T)T") # Date & time 4 test
test=" O_o $PWD ${git_tst[*]} $date o_O " # Test string
step=$[$COLUMNS-${#test}]; [[ $step -lt 0 ]] && step=0 # Count spaces
line="$GRN${line// /-}$DEF\n" # Create lines
home="$BLD$BLU$PWD$DEF" # Home dir info
date="$DIM$date$DEF" # Colored date & time
#------+-----+-------+--------+-------------+-----+-------+--------+
# Line | O_o |homedir| Spaces | Git status | Date| o_O | Line |
#------+-----+-------+--------+-------------+-----+-------+--------+
printf "$line $(face) $home %${step}s ${git_clr[*]} $date $(face) \n$line" # Final info string
}
PS1='${debian_chroot:+($debian_chroot)}\n$(info)\n$ '
case "$TERM" in xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)} $(face 1) \w\a\]$PS1";;
esac
Improved demure answer:
I think this is important because the exit status is not always 0 or 1.
if [ $EXIT != 0 ]; then
PS1+="${Red}${EXIT}:\u${RCol}" # Add red if exit code != 0
else
PS1+="${Gre}${EXIT}:\u${RCol}" # Also displays exit status
fi
To preserve the original prompt format (not just colors),
you could append following to the end of file ~/.bashrc:
PS1_ORIG=$PS1 # original primary prompt value
PROMPT_COMMAND=__update_prompt # Function to be re-evaluated after each command is executed
__update_prompt() {
local PREVIOUS_EXIT_CODE="$?"
if [ $PREVIOUS_EXIT_CODE != 0 ]; then
local RedCol='\[\e[0;31m\]'
local ResetCol='\[\e[0m\]'
local replacement="${RedCol}\u${ResetCol}"
# Replace username color
PS1=${PS1_ORIG//]\\u/]$replacement}
## Alternative: keep same colors, append exit code
#PS1="$PS1_ORIG[${RedCol}error=$PREVIOUS_EXIT_CODE${ResetCol}]$ "
else
PS1=$PS1_ORIG
fi
}
See also the comment about the alternative approach that preserves username color and just appends an error code in red to the end of the original prompt format.
You can achieve a similar result to include a colored (non-zero) exit code in a prompt, without using subshells in the prompt nor prompt_command.
You color the exit code portion of the prompt, while having it only appear when non-zero.
Core 2$ section of the prompt: \\[\\033[0;31;4m\\]\${?#0}\\[\\033[0;33m\\]\$ \\[\\033[0m\\]
Key elements:
return code, if not 0: \${?#0} (specificly "removes prefix of 0")
change color without adding to calculated prompt-width: \\[\\033[0;31m\\]
\\[ - begin block
\\033 - treat as 0-width, in readline calculations for cmdline editing
[0;31;4m - escape code, change color, red fg, underline
\\] - end block
Components:
\\[\\033[0;31;4m\\] - set color 0;31m fg red, underline
\${?#0} - display non-zero status (by removing 0 prefix)
\\[\\033[0;33m\\] - set color 0;33m fg yellow
\$ - $ or # on EUID
\\[\\033[0m\\] - reset color
The full PS1 I use (on one host):
declare -x PS1="\\[\\033[0;35m\\]\\h\\[\\033[1;37m\\] \\[\\033[0;37m\\]\\w \\[\\033[0;33m\\]\\[\\033[0;31;4m\\]\${?#0}\\[\\033[0;33m\\]\$ \\[\\033[0m\\]"
Note: this addresses a natural extension to this question, in a more enduring way then a comment.
Bash
function my_prompt {
local retval=$?
local field1='\u#\h'
local field2='\w'
local field3='$([ $SHLVL -gt 1 ] && echo \ shlvl:$SHLVL)$([ \j -gt 0 ] && echo \ jobs:\j)'"$([ ${retval} -ne 0 ] && echo \ exit:$retval)"
local field4='\$'
PS1=$'\n'"\e[0;35m${field1}\e[m \e[0;34m${field2}\e[m\e[0;31m${field3}\e[m"$'\n'"\[\e[0;36m\]${field4}\[\e[m\] "
}
PROMPT_COMMAND="my_prompt; ${PROMPT_COMMAND}"
Zsh
PROMPT=$'\n''%F{magenta}%n#%m%f %F{blue}%~%f%F{red}%(2L. shlvl:%L.)%(1j. jobs:%j.)%(?.. exit:%?)%f'$'\n''%F{cyan}%(!.#.$)%f '
Images of prompt

Implementing a portable file locking mechanism

I have implemented a file locking mechanism along the lines of the suggestion from the linux man page for "open", which states:
Portable programs that want to perform atomic file locking using a
lockfile, and need to avoid reliance on NFS support for O_EXCL, can
create a unique file on the same file system (e.g., incorporating
hostname and PID), and use link(2) to make a link to the lockfile. If
link(2) returns 0, the lock is successful. Otherwise, use stat(2) on
the unique file to check if its link count has increased to 2, in
which case the lock is also successful.
This seems to work perfectly, however to get 100% code coverage in my testing, I need to cover the case where the link count is increased to 2.
I've tried googling, but all I seem to be able to find is the same reference above regurgitated as "the way it's done".
Can anybody explain to me what set of circumstances would cause the link to fail (returns -1), but the link count is increased to 2?
The answer to your question is provided at the bottom of the link(2) page of the Linux Programmer's Manual:
On NFS file systems, the return code may be wrong in case the NFS
server performs the link creation and dies before it can say so. Use
stat(2) to find out if the link got created.
Creating another file is more trouble than anything. Create a directory instead and check the result of the creation. The Unix manual states that only one task can succeed in creating a directory, the other will get a failure if the directory already exists, including the case where 2 task tried it at the same time. The OS itself handles the issue so you don't have to.
If it wasn't for possible stale locks, that is all you would have to do. However, things happen, programs abort and do not always remove their lock. So the implementation can be a little bit more elaborate.
In a script I have often used the code below. It handles stale locks automatically. You can implement the same in C. Check man page:
man -s 2 mkdir
EXECUTION_CONTROL_FILE: is a name PATH and Dir name, something like /usr/tmp/myAppName
second_of_now: return the current time in seconds (included below)
LOCK_MAX_TIME: is how long in seconds a lock can exists before it is considered stale
sleep 5: It is always assumed that a lock will do something short and sweet. If not, maybe your sleep cycle should be longer.
LockFile() {
L_DIR=${EXECUTION_CONTROL_FILE}.lock
L_DIR2=${EXECUTION_CONTROL_FILE}.lock2
(
L_STATUS=1
L_FILE_COUNT=2
L_COUNT=10
while [ $L_STATUS != 0 ]; do
mkdir $L_DIR 2>/dev/null
L_STATUS=$?
if [ $L_STATUS = 0 ]; then
# Create the timetime stamp file
second_of_now >$L_DIR/timestamp
else
# The directory exists, check how long it has been there
L_NOW=`second_of_now`
L_THEN=`cat $L_DIR/timestamp 2>/dev/null`
# The file does not exist, how many times did this happen?
if [ "$L_THEN" = "" ]; then
if [ $L_FILE_COUNT != 0 ]; then
L_THEN=$L_NOW
L_FILE_COUNT=`expr $L_FILE_COUNT - 1`
else
L_THEN=0
fi
fi
if [ `expr $L_NOW - $L_THEN` -gt $LOCK_MAX_TIME ]; then
# We will try 10 times to unlock, but the 10th time
# we will force the unlock.
UnlockFile $L_COUNT
L_COUNT=`expr $L_COUNT - 1`
else
L_COUNT=10 # Reset this back in case it has gone down
sleep 5
fi
fi
done
)
L_STATUS=$?
return $L_STATUS
}
####
#### Remove access lock
####
UnlockFile() {
U_DIR=${EXECUTION_CONTROL_FILE}.lock
U_DIR2=${EXECUTION_CONTROL_FILE}.lock2
(
# This 'cd' fixes an issue with UNIX which sometimes report this error:
# rm: cannot determine if this is an ancestor of the current working directory
cd `dirname "${EXECUTION_CONTROL_FILE}"`
mkdir $U_DIR2 2>/dev/null
U_STATUS=$?
if [ $U_STATUS != 0 ]; then
if [ "$1" != "0" ]; then
return
fi
fi
trap "rm -rf $U_DIR2" 0
# The directory exists, check how long it has been there
# in case it has just been added again
U_NOW=`second_of_now`
U_THEN=`cat $U_DIR/timestamp 2>/dev/null`
# The file does not exist then we assume it is obsolete
if [ "$U_THEN" = "" ]; then
U_THEN=0
fi
if [ `expr $U_NOW - $U_THEN` -gt $LOCK_MAX_TIME -o "$1" = "mine" ]; then
# Remove lock directory as it is still too old
rm -rf $U_DIR
fi
# Remove this short lock directory
rm -rf $U_DIR2
)
U_STATUS=$?
return $U_STATUS
}
####
second_of_now() {
second_of_day `date "+%y%m%d%H%M%S"`
}
####
#### Return which second of the date/time this is. The parameters must
#### be in the form "yymmddHHMMSS", no centuries for the year and
#### years before 2000 are not supported.
second_of_day() {
year=`printf "$1\n"|cut -c1-2`
year=`expr $year + 0`
month=`printf "$1\n"|cut -c3-4`
day=`printf "$1\n"|cut -c5-6`
day=`expr $day - 1`
hour=`printf "$1\n"|cut -c7-8`
min=`printf "$1\n"|cut -c9-10`
sec=`printf "$1\n"|cut -c11-12`
sec=`expr $min \* 60 + $sec`
sec=`expr $hour \* 3600 + $sec`
sec=`expr $day \* 86400 + $sec`
if [ `expr 20$year % 4` = 0 ]; then
bisex=29
else
bisex=28
fi
mm=1
while [ $mm -lt $month ]; do
case $mm in
4|6|9|11) days=30 ;;
2) days=$bisex ;;
*) days=31 ;;
esac
sec=`expr $days \* 86400 + $sec`
mm=`expr $mm + 1`
done
year=`expr $year + 2000`
while [ $year -gt 2000 ]; do
year=`expr $year - 1`
if [ `expr $year % 4` = 0 ]; then
sec=`expr 31622400 + $sec`
else
sec=`expr 31536000 + $sec`
fi
done
printf "$sec\n"
}
Use like this:
# Make sure that 2 operations don't happen at the same time
LockFile
# Make sure we get rid of our lock if we exit unexpectedly
trap "UnlockFile mine" 0
.
. Do what you have to do
.
# We need to remove the lock
UnlockFile mine

Makefile errors while executing in Linux

I have one requirement in my automation.
I need to pass values like 1, 2, 3 to MY_IMAGE in command line in Linux.
I had defines activities for all these inputs in other make file.
The code similar to below i wrote for my requirement. Issue was whenever I passes values like MY_IMAGE=1, MY_IMAGE=2, MY_IMAGE=3
it's printing only echo ACT_DO=XYZ;
It's not displaying the other info whenever I selected 2 or 3. Can anyone check and correct my code.
export MY_IMAGE
MY_IMAGE=$img_value;
if [ $img_value :="1" ]
then
echo ACT_DO=XYZ;
else
if [ $img_value :="2 ]
then
echo ACT_DO=ABC;
else
if [ $img_value :=3 ]
then
echo ACT_DO=ETC;
else
echo ""$img_value" is unsupported";
exit 1;
fi
fi
fi
Your code has a quote in the wrong place, and uses := which doesn't mean anything, as far as I know. It's also implemented confusingly.
Try this:
export MY_IMAGE
MY_IMAGE=$img_value
case "$img_value" in
1 ) echo ACT_DO=XYZ ;;
2 ) echo ACT_DO=ABC ;;
3 ) echo ACT_DO=ETC ;;
* )
echo "\"$img_value\" is unsupported"
exit 1
;;
esac
The first two lines are not required for this code, but I presume you wanted that for something else.

Resources