1

Stormvirux provided this nice script in another thread. It puts column headings on the output of an ls -l listing:

#!/bin/bash
{ echo Permissions links Owner Group Size Last_modMonth Last_modTime Last_modTime Filename; ls -l ; } | column -t | awk 'NR!~/^(2)$/'
ls -l | head -1

Just running it on the command line works great. I like it and want to use it as an alias for, say lsl on a Linux system running bash.

But I can't for the life of me figure out how to make the delimiters work so it is interpreted correctly. When I try just using the alias command on the command line (which I do before I commit it to a configuration file like .bashrc), it won't work. I get various errors when I try various ways to package it so it's interpreted correctly.

Can someone tell me how to get this working as an alias, or point me to a good reference that can clearly tell me what I need to do to get something like this working as an alias?

  • 1
    This is not at all similar to the proposed duplicate, which is about multiple-word alias names. – Michael Homer Aug 21 '14 at 5:26
  • ... and further, the top answer is about a git-specific method of doing it. – derobert Aug 21 '14 at 16:24
3

Another way, you can define it as a function in your .bashrc:

lsl() {
  { echo Permissions links Owner Group Size Last_modMonth Last_modTime Last_modTime Filename;
  ls -l; } | 
  column -t | 
  awk 'NR!~/^(2)$/'
  ls -l | head -1
}
2

If you must do it as an alias:

alias lsl='{ echo Permissions links Owner Group Size Last_modMonth Last_modTime Last_modTime Filename; ls -l ; } | column -t | awk '\''NR!~/^(2)$/'\'';ls -l | head -1'

We need to escape the internal single quotes with backslashes so they aren't interpreted as stopping the string.

If we use double quotes instead then the ! is interpreted as a history expansion and needs even more escaping, which is probably the most confusing problem you ended up with (something like "bash: !~/^: event not found", which is incomprehensible gibberish).


The above will work, but better would just be to put that file somewhere in your path and make it executable. Create, say, ~/.local/bin and a script lsl with exactly the contents of your post inside there, then chmod +x ~/.local/bin/lsl and add a line to your .bashrc:

export PATH="$HOME/.local/bin:$PATH"

to make sure that executables in that directory will be found. Then you can just write lsl anywhere to run the code. This approach is more maintainable and easier to understand.

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.