Run cd build only if mkdir build succeeds.
Do not run cd when mkdir fails.
Which one-line command is appropriate?
&& executes the right command only when the left command exits with status zero.
Detailed explanation
mkdir build ; cd buildIncorrect. A semicolon runs cd even if mkdir fails.
mkdir build && cd buildCorrect. mkdir build && cd build conditions cd on successful creation.
mkdir build || cd buildIncorrect. || runs the right side on failure.
mkdir build | cd buildIncorrect. A pipe connects output and input rather than testing success.
Try it yourself
An example you can run in a temporary verification environment.
tmp=$(mktemp -d); cd "$tmp"; mkdir build && cd build; pwd; cd /; rm -rf "$tmp"Expected result
末尾が/buildの一時パスKey points
- && is an AND list
- Zero means success
- The right side runs on success only
Notes
- Environment: Bash 5.x / 一時ディレクトリ
- Use disposable shell sessions and harmless commands for experiments.
- Shell behavior can depend on Bash options and distribution defaults.
Foundation review
Place the operation
The AND operator protects a dependent step from running after a failed prerequisite.
Check the side effect
Make the first command fail intentionally and confirm that the dependent command is skipped.