In the script, I used main function to create a new sudo-bash to finish all the things with sudo.
#!/bin/bash
function sudo_stuffs() {
install_ss
}
function install_ss() {
echo something
}
main() {
# 切换目录
cd /tmp
if [[ ! -d "install_shadowsocks" ]]; then
mkdir install_shadowsocks
fi
cd install_shadowsocks
# 如果没有sudo权限
if ! sudo -v 1>/dev/null 2>&1 ; then
# 提示登录有权限的账户
echo "--- You don't have authority, login to the root or others in sudoers. ---"
exit 1
fi
export -f install_ss
FUNC=$(declare -f sudo_stuffs)
sudo bash -c "$FUNC; sudo_stuffs"
}
main "$@"
But actually in the sudo_stuffs function, there are more detailed functions like install_ss function.
I even used export -f install_ss to make sure install_ss could be found in the sub shell called with sudo bash -c "$FUNC; sudo_stuffs".
But still, the result came with
bash: line 2: install_ss: command not found
what can I do please?
FUNC=$( declare f sudo_stuffs install_ss )? Also, I would probably doeval "$FUNC"instead of using$FUNCunquoted../scriptname.shor did you call it explicitly as a shell argument (likebash scriptname.sh)?main(), you never call it inside the script.sudo -Edoesn't work? It can transfer string environment variables to the newborn shell if there is aexport a="1"before thesudo bash -c "$FUNC; sudo_stuffs"line. But theexport -f install_ssfailed.sudois considered a security flaw by some, and it can be configured to be not allowed in thesudoersfile.