找不到命令,并且不存在的 Mac 终端行上的文件意外结尾



我对mac终端很陌生,对bash不太了解,但我已经尝试纠正这些错误有一段时间了,但一直没能找到它们。这是我的代码:

#!/bin/bash
#change password of any mac user
# show users and select a valid one
Users=$(ls -1 /Users)
ok=0
while [ "$ok" == "0" ]; do
    echo "Users"
    echo "----------------"
    echo $Users
    echo "----------------"
    echo "Select user"
    read -e user
    foreach i in $Users; do
        if [ "$user" == "$i" ]; then
            clear
            echo 'User chosen:'
            echo $user
            echo "---------------"
            ok=1
            break
        fi
    done
        if [ "$ok" == "0" ]; then
            clear
            echo "There is no such user"
            echo 'Try again'
        fi
done
# get password and comfirmation
password=0
password1=1
while [ "$password" != "$password1" ]; do
    echo "Enter password"
    read -e password
    clear
    echo "Confirm password"
    read -e password1
    clear
    echo "Passwords are not the same"
    echo "Try again"
done
clear
echo "Password saved"
echo "--------------"
# get version and change password
vrs=$(sw_vers -productVersion)
version=${vrs:0:4}
if [ $version -ge 10.7 ]; then
       #LION
       launchctl load /System/Library/LaunchDaemons/com.apple.opendirectoryd.plist
       dscl . -passwd /Users/"$user" "$pass" 
else
       #SNOW LEOPARD
       launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist
       dscl . -passwd /Users/"$user" "$pass"
fi
echo "Password for user"
echo $user
echo "Succesfully changed"
echo "Press enter to end"
read -e end
exit 0

我得到的输出是:

:command not found
:command not found
mac.sh: line 65: syntax error: unexpected end of file

我已经检查了我的$PATH及其正确性。此外,我尝试运行而不是"sh-mac.sh"sh./mac.sh"

  1. foreach更改为for

  2. $pass更改为$password,因为这是您保存密码的地方

如果仍然不起作用,那么将第一行更改为#!/bin/bash -x,再次运行并将输出粘贴到问题中。

事实上,您不应该实现所有的密码输入功能。您应该让dscl实用程序来做这件事,如下所示:

dscl . -passwd /Users/"$user"

我会这样重写你的脚本:

#!/bin/bash
userhomes=/Users
echo Users
echo "----------------"
ls -1 $userhomes
echo "----------------"
echo "Select user"
while :; do
    read -e user
    if test "$user" -a -d $userhomes/$user; then
        clear
        echo 'User chosen:'
        echo $user
        echo "---------------"
        break
    else
        clear
        echo "There is no such user"
        echo 'Try again'
    fi
done
vrs=$(sw_vers -productVersion)
case "$vrs" in
    10.[7-9]*)
       #LION
       launchctl load /System/Library/LaunchDaemons/com.apple.opendirectoryd.plist
       ;;
    *)
       #older
       launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist
       ;;
esac
dscl . -passwd $userhomes/"$user"

一个问题是foreach循环的语法。Bash没有foreach命令,但它有做同样事情的for循环:

for i in $Users ; do
  #do something
done; 

最新更新