diff --git a/sh/tests/check-user_test.sh b/sh/tests/check-user_test.sh new file mode 100755 index 000000000..d00340c75 --- /dev/null +++ b/sh/tests/check-user_test.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash + +# set -euo pipefail +IFS=' +' + +script_dirS=$(cd -P "$(dirname "$BASH_SOURCE")" &>/dev/null && pwd) + +challenge() { + submitted="./check-user.sh $@ + " + expected="./check-user.sh $@ + " + submitted+=$(2>&1 bash "$script_dirS"/student/check-user.sh "$@") + expected+=$(2>&1 bash "$script_dirS"/solutions/check-user.sh "$@") + + diff -U 1 <(echo "$submitted") <(echo "$expected") +} + +challenge "-i" "root" +challenge "-e" "root" + +challenge "-i" "unknown_not_found" +challenge "-e" "unknown_not_found" + +challenge +challenge "-i" "root" "too" "many" "args" +challenge "-t" "root" + diff --git a/sh/tests/solutions/check-user.sh b/sh/tests/solutions/check-user.sh new file mode 100644 index 000000000..29ae06879 --- /dev/null +++ b/sh/tests/solutions/check-user.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +set -euo pipefail +IFS=' +' + +if [ $# != 2 ] +then + >&2 echo "Error: expect 2 arguments" + exit 1 +elif [[ $1 == "-e" ]] +then + user_info=$(getent passwd $2) + if [[ $user_info == "" ]] + then + echo no + else + echo yes + fi +elif [[ $1 == "-i" ]] +then + getent passwd $2 +else + >&2 echo "Error: unknown flag" + exit 1 +fi \ No newline at end of file diff --git a/subjects/devops/check-user/README.md b/subjects/devops/check-user/README.md new file mode 100644 index 000000000..187b05eb1 --- /dev/null +++ b/subjects/devops/check-user/README.md @@ -0,0 +1,39 @@ +## Check User + +### Instructions + +In this exercise you will make a script `check-user.sh` that will take 2 arguments and return information about the selected user, always ended by a new line. + +The first argument will be a flag defining the behavior of the script: +- `-e`: check if the user exists, returns `yes` or `no` appropriately. +- `-i`: returns information about the user. + +The second argument will be the name of the checked user. + +> The information about the user will be formatted in the same way it appears in `/etc/passwd`. + +### Usage + +```console +$ ./check-user.sh -e root +yes +$ ./check-user.sh -i root +root:x:0:0:root:/root:/bin/bash +$ ./check-user.sh -e unknown +no +$ ./check-user.sh -i unknown +$ +``` + +> Your results may appear slightly different. + +### Error handling + +All errors will print a specific message on **stderr** (ending with a newline) and returns a specific non-zero value: +- Wrong number of arguments: `"Error: expect 2 arguments"`, returns `1`. +- First argument different from `-e` or `-i`: `"Error: unknown flag"`, exit with `1`. + +### Hints + +> `man getent` will be a great resource to explore +> [List Linux users](https://linuxize.com/post/how-to-list-users-in-linux/)