I'm creating a bash script to perform some tasks stored in an array, and some of them need elevated permissions. This is my working current approach using Zenity:
#!/bin/bash
functions=("function1")
functions+=("function2")
function1()
{
password=$1
echo $password | sudo -S fdisk -l
}
function2()
{
password=$1
echo $password | sudo -S fdisk -l
}
password=$(zenity --password)
for i in ${!functions[@]}
do
${functions[$i]} $password
done
But I would like to avoid passing the password every time, something similar to this:
#!/bin/bash
functions=("function1")
functions+=("function2")
function1()
{
sudo -S fdisk -l
}
function2()
{
sudo -S fdisk -l
}
password=$(zenity --password)
# Become superuser here with given password
for i in ${!functions[@]}
do
${functions[$i]}
done
I know the usual approach is to have a separated script, but in this case I need the work to be done in just one script. I have tried this:
echo $password | sudo -S ${functions[$i]}
But then bash throws a "sudo: function1: order not found" error. Can anyone tell me what am I doing wrong here?
Edit: the goal here is either to become superuser at one point and mantain sudo privileges (without calling the script with sudo) or just use the password variable in only one line of code. Is it possible?
答案 0 :(得分:0)
只需使用全局变量。
functions=("function1")
functions+=("function2")
function1()
{
echo "$password" | sudo -S fdisk -l
}
function2()
{
echo "$password" | sudo -S fdisk -l
}
password=$(zenity --password)
for i in ${!functions[@]}
do
${functions[$i]}
done