If you install GNU tar
by means of installing the gnu-tar
package using Homebrew on macOS, you will notice the following message in the terminal:
GNU "tar" has been installed as "gtar".
If you need to use it as "tar", you can add a "gnubin" directory
to your PATH from your bashrc like:
PATH="/usr/local/opt/gnu-tar/libexec/gnubin:$PATH"
This means that your tar
command at the start of your question will work as expected if you first set PATH
as shown in the gnu-tar
installation message above.
PATH="/usr/local/opt/gnu-tar/libexec/gnubin:$PATH"
tar --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2020-01-01' -cvf api.tar api
Updating PATH
conditionally:
if [ "$(uname)" = Darwin ]; then
PATH="/usr/local/opt/gnu-tar/libexec/gnubin:$PATH"
fi
tar --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2020-01-01' -cvf api.tar api
You could also test with command -v
:
if command -v gtar >/dev/null 2>&1; then
tar=gtar
elif command -v tar >/dev/null 2>&1 && tar --version | grep -q -F GNU 2>/dev/null; then
tar=tar
else
echo 'No GNU tar available' >&2
exit 1
fi
"$tar" --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2020-01-01' -cvf api.tar api
This tests whether gtar
exists as a command. If it does, the variable tar
is set to the string gtar
. If it doesn't exist, we test for tar
, and if tar
exists we test whether tar --version
returns something that contains the substring GNU
and assign the variable tar
the string tar
. But if the tests fail, we bail out with a diagnostic message.
Later, if we didn't bail out with an error message, we use "$tar"
as the command.
You could also choose to use a test on the output of uname
, obviously,
if [ "$(uname)" = Darwin ]; then
# Assumes GNU tar is gtar on macOS and that it's available
tar=gtar
else
# Assumes GNU tar is tar on this system, and that it's available
tar=tar
fi
"$tar" --sort=name --owner=root:0 --group=root:0 --mtime='UTC 2020-01-01' -cvf api.tar api
ARGS
, then callgtar $ARGS
followed bytar $ARGS
. If you use Bash interactively, you should also look up "quick substitution". – berndbausch Sep 19 '21 at 22:11UTC 2020-01-01
). See: https://unix.stackexchange.com/q/444946/170373 – ilkkachu Sep 20 '21 at 10:25