1

macOS Ventura with a 'MacPorts' installation that includes GNU replacements for numerous "Apple-sourced" utilities including ls. The original ls is located at /bin/ls, the GNU/MacPorts version of ls is located at /opt/local/libexec/gnubin/ls.

The GNU version of ls works for most things, but in some cases (one in particular) I need the "Apple-sourced" version of ls. For example, to list the 'file flags' (ref man chflags), I need the O option... the GNU version does not provide this.

I'd like to set an alias in ~/.zshrc that handles ls -lO, and possibly other options unique to the "Apple-sourced" version of ls.

I've tried several aliases in ~/.zshrc that didn't work; e.g.

alias ls -lO='/bin/ls -lO'

How to do this?

1
  • 1
    The syntax is wrong. It is alias WORD=REPLACEMENT, but you have two words to the left of the equal sign. You could write a shell script or function ("shell script" would be more generally usable) with name ls, which inspects the parameters and based on them calls the desired ls` version. However I find this fiddling with ls error prone; for instance, which ls should be executed for ls -Ol? Commented Feb 14, 2025 at 8:55

1 Answer 1

4

A conventional alias won't work, but you can declare a function in ~/.zshrc that should do what you need. It uses a case conditional that will allow you to add other options for ls:

function ls() {
  case $* in
    -lO* ) shift 1; command /bin/ls -lO "$@" ;;
    * ) command ls "$@" ;;
  esac
}

Note that for the -lO option; the "Apple-sourced" version of ls at /bin/ls is executed, whereas (as shown above) all other options are passed through to the GNU/MacPorts version of ls. Of course this assumes that your PATH environment is set to favor the GNU utilities; something like this:

% echo $PATH
/opt/local/libexec/gnubin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

To take effect you should add the function definition above to your ~/.zshrc file, and then source it to (each) shell you plan to use. After adding the ls function to ~/.zshrc, it can be sourced as follows:

% source ~/.zshrc
--OR--
% . ~/.zshrc 

After sourcing ~/.zshrc, we can verify correct operation as follows:

% ls -lO /etc/auto_master
-rw-r--r--  1 root  wheel  schg 284 Feb 13 22:47 /etc/auto_master
#                          ^^^^^^^^

% ls --version
ls (GNU coreutils) 9.5
Copyright (C) 2024 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Richard M. Stallman and David MacKenzie.
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.