2

I have tried to made an alias ls -a = ls -A, ending up with:

bash: alias: `ls -a': invalid alias name

I want ls -a without . and ... How can I get that?

  • 1
    Is there something stopping your from just using ls -A? Sorry, but I'm not sure I understand. You want to type ls -a, but you want it to execute ls -A? Since an alias needs to be a single word, what abut using lA instead? – Kusalananda Feb 21 at 11:59
  • my muscle memory...i giess! it always forget that shift, and i get ls -a! :) – BaRud Feb 21 at 17:29
1

You cannot use alias like that. Aliases are single names and are invoked without any arguments (all arguments are passed to aliased commands directly without modification).

My proposition to solve the problem you are facing is to use a function and only then alias it to ls, like that:

_ls() {
      if [[ "$1" == "-a" ]]; then
          shift
          ls -A "$@"
      else
          ls "$@"
      fi
}
alias ls=_ls

Notice that this way only ls -a will be affected (-a needs to be alone on the first position), so you can still access "standard" -a by putting it on other places or gather it with other options:

ls -a              # modified '-a'
ls -a -l /tmp      # modified '-a'
ls -al             # not modified
ls -l -a /tmp      # not modified 
  • 1
    Might be worth mentioning that OP's alias syntax has some errors as well. – Jesse_b Feb 21 at 14:54
  • What's the reason for using both an alias and a function here? – Kusalananda Feb 21 at 17:31
  • @Kusalananda My bash version (4.4.23) doesn't allow to create function in the form fun() { } with the same name as previously defined alias (and for ls that's often the case by default for many distributions). I can do that with function fun form, but then $1 doesn't return argument of function, but rather argument of previously defined alias. By creating a function and then "re-alias" this we fix the problem in somewhat convoluted way. – jimmij Feb 21 at 18:36
  • @jimmij unalias ls? – Kusalananda Feb 21 at 18:37
  • @Kusalananda but then you lose all previously defined switches like --color etc. – jimmij Feb 21 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.