Tuesday, February 6, 2024

[SOLVED] How to add condition before reboot Linux machine

Issue

We want to add some important test before init 6 will take effect ( on redhat )

As the following

We add the function ( init ) in /root/.bashrc

init () {
    /home/sanity.sh
    [[ $? –eq 0 ]] && echo "reboot will performed" || 
         echo "reboot will not performed because sanity.sh exit with error" && exit 1
    Sleep 1
    init $@    
}

But from some unclear reason init 6 not performed

What is wrong in my function?

Goal – before init 6 command , we want to get status from /home/sanity.sh Script

If status is 0 then init 6 will done , if not then init 6 will not allowed !


Solution

If your test is re-written to print what it does, rather than do it, firstly passing:

~$> x=0
~$> [[ $x -eq 0 ]] && echo "pass1" || echo "fail1" && echo "exit"
pass1
exit

Then failing:

~$> x=1
~$> [[ $x -eq 0 ]] && echo "pass1" || echo "fail1" && echo "exit"
fail1
exit

so you need to group everything after the || so the exit is only performed if test fails:

~$> x=0
~$> [[ $x -eq 0 ]] && echo "pass1" || { echo "fail1" && echo "exit"; }
pass1

Then you will need to use command to actually call init:

The command utility shall cause the shell to treat the arguments as a simple command, suppressing the shell function lookup that is described in Section 2.9.1.1, Command Search and Execution, item 1b.



Answered By - Guy
Answer Checked By - Mildred Charles (WPSolving Admin)