tar -C: Change Directory (Usage & CI Errors)
tar -C makes tar cd into a directory before reading or writing members.
The -C flag is how you control the path prefix stored in an archive and where files land on extract. Used well it removes ugly leading directories; used badly it scatters files or stores absolute-looking paths.
What it does
tar -C <dir> changes to <dir> before processing the paths that follow it. On create it controls the prefix stored in the archive; on extract it controls the destination. You can use -C multiple times to pull files from different roots into one archive.
Common usage
tar -czf dist.tar.gz -C build . # store build/ contents, no prefix
tar -xzf dist.tar.gz -C /opt/app # extract into /opt/app
tar -cf out.tar -C src a.txt -C ../docs b.md # multiple rootsOptions
| Form | What it does |
|---|---|
| -C <dir> (before paths) | cd into <dir>, then add/extract the next paths |
| -C <dir> repeated | Switch root again for following members |
| -C <dir> on extract | Unpack into <dir> instead of the current dir |
| tar -czf x.tgz -C build . | Archive contents without the build/ prefix |
In CI
To ship build output without a leading folder, use tar -C build . so the archive holds index.html, not build/index.html. On the consumer job, tar -xzf dist.tar.gz -C ./public drops those files exactly where the server expects them.
Common errors in CI
Order matters: -C must come before the paths it affects. tar -czf out.tgz . -C build adds the current directory first, then tries to cd, which is rarely what you want. tar: build: Cannot open: No such file or directory means the target directory does not exist; create it with mkdir -p before extracting into it.