I am working on a script and this contains a function to create a new user and this function needs to be run as root to work but when I run my script as:
sudo ./sample.sh
It throws the following error:
./sample: 3: Syntax error: "(" unexpected
But when I run it without sudo I get this output:
-
-
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
-
-
Thus the script is working with my standard user (it's just a privilege problem). I don't understand why it is not working with sudo. I find in the internet that I need to export the function but still same problem, here's the script:
############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 $1 ]
then
echo -e 'e\1[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=$1
User_Create
fi
Why does a funtion in bash script throws syntax error …?
The line
#!/bin/bash
has no effect - it would have to be the first line; so the script may from different environments be executed by different shells, some of which have an incompatible syntax.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.