Help needed - Script

Hi guys,

Hoping someone can help me with the below.

  • Write a script called 'home.sh' which takes a username as its argument and
    will print out the home directory of that user as follows:
$ ./home.sh root
root's home directory is /root
$ ./home.sh nobody
nobody's home directory is /

If the command is used incorrectly, print a usage error to stderr:

Practice questions - University Of Technology Sydney

Hello edujs7,

IMHO you should open 1 thread for each question, else people who are seeing this thread in future could be confused. So I am answering very first question of yours. Could you please try following.

cat script.ksh
user_name="$1"
awk -v user="$user_name" -F':' '$1==user{print "Home directory for user " user " is: "$(NF-1)}'  /etc/passwd

Thanks,
R. Singh

1 Like

Many thanks for your help RavinderSingh13 and as per your suggestion I did edit the post and will create other threads for the other questions.

1 Like

If you forgo the required error message, this could work for you:

echo "$1's home directory is $(grep $1 /etc/passwd | cut -d: -f6)"

To produce the error checking and message, a serious detour must be taken, and we need to know what your OS and shell versions are.

1 Like
getent passwd "$1" | cut -d: -f6

Be aware that not everyone has some of the more esoteric utilities:

Last login: Thu Apr 25 14:55:41 on ttys000
AMIGA:amiga~> getent
-bash: getent: command not found
AMIGA:amiga~> _
1 Like

Then another option to run as root

runuser -l "$1" -c 'echo $HOME'

but will give an error if the user does not exist

--- Post updated at 17:19 ---

Purely for educational purposes. Maybe even so?

su -c 'echo $HOME' "$1"

This can produce multiple answers if $1=ann and both ann and anna are users in /etc/passwd

1 Like

@jgt: absolutely, thanks. Try grep ping for "^$1:"

With bash,zsh,ksh the ~$var expansion works in eval .

#!/bin/bash
eval home=~$1
echo "$1's home directory is $home"
  • eval is evil. Make it as short and simple as possible!
  • in csh it works without eval. The whole csh is evil!