0

I have the following script for creating a new user on macOS:

#!/bin/bash

export PATH=/usr/bin:/bin:/usr/sbin:/sbin

consoleUser() {
    echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ && ! /loginwindow/ { print $3 }'
}

displayfortext() { # $1: message $2: default text
    message=${1:-"Message"}
    defaultvalue=${2:-"default value"}
    user=$(consoleUser)
    if [[ $user != "" ]]; then
        uid=$(id -u "$user")

        launchctl asuser $uid /usr/bin/osascript <<-EndOfScript
            text returned of ¬
                (display dialog "$message" ¬
                    default answer "$defaultvalue" ¬
                    buttons {"OK"} ¬
                    default button "OK")
            EndOfScript
    else
        exit 1
    fi
}
realname=$(displayfortext "Enter the real Name (e.g. John Doe)" "John Doe")
username=$(displayfortext "Enter the Username (e.g. john.doe)" "john.doe")
sudo dscl . -create /Users/$username RealName $realname #Set Real Name (e.g. John Doe)

Now after the last sudo command (and a few others I left out) the user is successfully created. The problem is, that the users name (John Doe) is only "John" and everything behind the whitespace disappeared.

Does someone have an idea how to fix this? I do not want another character between John and Doe (nothing like John_Doe) it has to be a whitespace (company policy).

LWun
  • 71
  • 1
  • 11
  • In your dscl command, you are using bash variables `username` and `realname`, but I don't see where they are assigned a value. – user1934428 Mar 23 '20 at 08:17
  • I added the username line - realname declaration was in there already (2nd and 3rd line from bottom). – LWun Mar 23 '20 at 08:36

1 Answers1

1

bash breaks the arguments on white space. Hence, if realname contains a white space, the individual words in it become two different parameters. Quote the parameter as "$realname" to avoid this.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • I did change `realname=$(displayfortext "Enter the real Name (e.g. John Doe)" "John Doe")` to `$"realname"=$(displayfortext "Enter the real Name (e.g. John Doe)" "John Doe")`. Now there's no name at all after creating the user. – LWun Mar 23 '20 at 08:53
  • This change does not make sense!!! As I said, the problem is in **passing the parameter**, so you have to quote it of course in your `dscl` command, not at the place where you assign the variable, and the quoting is not `$"realname"`, but `"$realname"`! – user1934428 Mar 23 '20 at 08:58
  • @LWun : You can read [here](https://www.tldp.org/LDP/abs/html/quotingvar.html) about quoting in bash. – user1934428 Mar 23 '20 at 09:00