Conditions: if / elif / else
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
if command; then
...
elif another_command; then
...
else
...
fi
if checks a command's exit code: 0 is true. [ … ] is just a command that returns 0 or 1. That's why you can put any command into an if:
if grep -q "^kai:" /etc/passwd; then
echo "the user kai exists"
fi
if ping -c1 -W1 8.8.8.8 > /dev/null 2>&1; then
echo "there is internet"
fi
if ! command -v git > /dev/null; then
echo "git isn't installed" >&2
exit 1
fi
then can go on the same line after a ; (as above) or on the next line. An if is closed with the word fi — that's if backwards.
>&2 prints a message to the error stream, and exit 1 ends the script with an error code.
Task. The script gets a path as an argument. Print file if it's a file (and on the second line its number of lines), dir if it's a folder, missing if there's nothing there. Before each test, the starter code creates notes.txt (2 lines) and the folder docs.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.