سؤال

I have the following piece of code:

read password1
echo "$password1" | sudo -Sk foo_bar

Is there any method by which I can detect if authentication failed (e.g. incorrect password, or user not a sudoer) while executing sudo? Checking the value of $? doesn't work, since foo_bar may return 1, as does sudo when authentication fails, leaving me with no way to inform the user if the password was wrong or the command went into an error.

هل كانت مفيدة؟

المحلول

You can authenticate with a separate invocation of sudo:

if ! echo "$password1" | sudo -Sv -p ''; then
    echo "Authentication failed" >&2
else
    sudo foo_bar
fi

Note that this approach will fail if sudo's authentication timeout has been disabled (i.e. if timestamp_timeout is set to 0 in /etc/sudoers).

نصائح أخرى

Using debug mode -

#!/bin/bash -xv  

-x added will show each and every statement in debug mode.

OR

While executing Shell script you can create error logs using the below lines -

./filename.sh > /path/to/error_log/backup.log 2>&1 

You can echo the statements and get to know the execution of statements

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top