user4035
user4035

Reputation: 23729

How to get the first element of a string split with space

I am trying to get the name of the user after su in a bash script. I used the following code:

user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user

It works correctly, but is it possible to achieve the same result with less number of commands?

Upvotes: 24

Views: 43022

Answers (3)

Inian
Inian

Reputation: 85590

Use bash parameter-expansion without needing to use arrays,

myUser=$(who am i)
printf "%s\n" "${myUser%% *}"
user4035

(or) just use a simple awk, command,

who am i | awk '{print $1}'
user4035

i.e. in a variable do,

myUser=$(who am i | awk '{print $1}')
printf "%s\n" "$myUser"

(or) if your script is run with sudo privileges, you can use this bash environment-variable,

printf "%s\n" "${SUDO_USER}"

Upvotes: 34

Tomas
Tomas

Reputation: 1887

Another simple solution is cut with custom delimiter:

user=$(who am I | cut -d ' ' -f1)
echo $user

Upvotes: 12

Alnitak
Alnitak

Reputation: 339816

You can remove one line of commands by creating the array on one line, but it's not worth doing any more than that because at least you're only using shell builtins, and not forking any additional commands:

who=(`who am i`)
user=${who[0]}

Upvotes: 7

Related Questions