为什么 bash 脚本中的函数以 root 身份(使用 sudo)抛出语法错误,而以标准用户身份运行?

Why does a function in bash script throw syntax error as root (using sudo) while as standard user it works?

我正在编写一个脚本,它包含一个创建新用户的函数,这个函数需要 运行 作为 root 才能工作,但是当我 运行 我的脚本为:

sudo ./sample.sh

它抛出以下错误:

./sample: 3: Syntax error: "(" unexpected

但是当我 运行 它没有 sudo 我得到这个输出:

-
-
useradd: Permission denied.
useradd: cannot lock /etc/passwd; try again later.
chage: user 'yt' does not exist in /etc/passwd
chage: user 'yt' does not exist in /etc/passwd
-
-
sed: can't read /etc/sudoers: Permission denied
sed: can't read /etc/sudoers: Permission denied
-
-

因此该脚本适用于我的标准用户(这只是一个权限问题)。 我不明白为什么它不能与 sudo 一起使用。 我在互联网上发现我需要导出函数但仍然是同样的问题,这是脚本:

############create user Function#
#!/bin/bash
function user_create ()
{


        useradd -m -p '#SOME_PASSWD' -s /bin/bash $userName

        sudo chage  -m 5 -M 90 -I 30 -W 14  $userName
        sudo  chage --lastday 0  $userName
        echo ''
        echo '--------------------------------------------------------------------------------------------'
        echo -e '\e[32mPasswd set for \e[1m'$userName' for 90 days MAX | 5 days MIN\e[0m'
        echo -e '\e[32mPasswd is set to change the current passwd in next login for \e[1m' $userName
        echo -e '\e[0m--------------------------------------------------------------------------------------------'
        #User based policy#
        sed -i "#SOME_SED_COMMAND" /etc/sudoers
        sed -i "/#SOME_STRING/#NEW_STRING" /etc/sudoers

        echo -e '\e[33m'
        sudo cat /etc/sudoers | grep -i "$userName"
        echo -e '\e[0m'
        echo ''
        echo '------------------------------------------------------------------'
        echo -e '\e[1m\e[32mUser Privilege Set\e[0m'
        echo '------------------------------------------------------------------'

        return 0
}

export -f user_create

if [ -z  ]
then
        echo -e 'e[m e\[100m e\[33m Do you want to CREATE A NEW USER?e\[0m (y/n)'
        read createUser
        if [ $createUser = 'y' -o $createUser = 'Y' ]
        then
                echo 'Enter USER.NAME:::: First_Name.Last_Name'
                read userName
                user_create
        else
                echo ''
                echo '------------------------------------------------------------------'
                echo -e '\e[31mNO NEW USER added.\e[0m'
                echo '------------------------------------------------------------------'
        fi
else
        userName=
        User_Create

fi

Why does a funtion in bash script throws syntax error …?

#!/bin/bash

没有效果——它必须是第一行;因此来自不同环境的脚本可能会由不同的 shell 执行,其中一些具有不兼容的语法。