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?

jasonwryan
  • 73,126
garyZ
  • 11

2 Answers2

4

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
}
cuonglm
  • 153,898
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.

Michael Homer
  • 76,565