Command separators: ; && ||
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Several commands on one line:
cd /tmp; ls # ; — run them in turn, regardless of the result
mkdir build && cd build # && — the second one only if the first one SUCCEEDED
cd /nope || echo "no such folder" # || — the second one only if the first one FAILED
Success and failure are determined by the exit code: 0 is success, anything else is an error. The last code is kept in $?:
grep -q root /etc/passwd
echo $? # 0 — found
&& and || make up a short form of a condition:
[ -f config.txt ] && echo "there is a config" || echo "no config"
Be careful: if the command after && itself fails, the part after || runs too. For complex logic, use if.
An administrator's classic "chains":
sudo apt update && sudo apt upgrade -y
make && ./app
cd "$DIR" || exit 1 # don't continue the script if changing the folder failed
Task. The script gets a file name as an argument. If the file exists ([ -f "$1" ]), print found; otherwise create it and print created. Use && and ||, without if. Before each test the starter code creates the file notes.txt — for it the answer is found.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.