146

I want to create an alias in bash like this:

alias tail_ls="ls -l $1 | tail"

Thus, if somebody types:

tail_ls /etc/ 

it will only show the last 10 files in the directory.

But $1 does not seem to work for me. Is there any way I can introduce variables in bash.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Deepank Gupta
  • 1,597
  • 3
  • 12
  • 11

6 Answers6

222

I'd create a function for that, rather than alias, and then exported it, like this:

function tail_ls { ls -l "$1" | tail; }

export -f tail_ls

Note -f switch to export: it tells it that you are exporting a function. Put this in your .bashrc and you are good to go.

Aditya Sanghi
  • 13,370
  • 2
  • 44
  • 50
Maxim Sloyko
  • 15,176
  • 9
  • 43
  • 49
43
alias tail_ls='_tail_ls() { ls -l "$1" | tail ;}; _tail_ls'
Javier López
  • 823
  • 8
  • 14
  • 6
    That's a creative approach. Definitely solves the issue if they **need** to use an alias rather than a function… I think I'd prefer a function if those are an option instead, but a very neat solution to keep in mind for when the right situation arises! – lagweezle Jul 21 '16 at 16:00
38

The solution of @maxim-sloyko did not work, but if the following:

  1. In ~/.bashrc add:

    sendpic () { scp "$@" mina@foo.bar.ca:/www/misc/Pictures/; }
    
  2. Save the file and reload

    $ source ~/.bashrc
    
  3. And execute:

    $ sendpic filename.jpg
    

original source: http://www.linuxhowtos.org/Tips%20and%20Tricks/command_aliases.htm

fedorqui
  • 275,237
  • 103
  • 548
  • 598
jruzafa
  • 4,156
  • 1
  • 24
  • 26
4

You can define $1 with set, then use your alias as intended:

$ alias tail_ls='ls -l "$1" | tail'
$ set mydir
$ tail_ls
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
3

tail_ls() { ls -l "$1" | tail; }

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • 1
    Please fix the syntax error (missing `;` before `}`) and double-quote `$1` so as to also support filenames with embedded whitespace and other shell metacharacters. – mklement0 Feb 21 '16 at 22:22
0

If you are using the Fish shell (from http://fishshell.com ) instead of bash, they write functions a little differently.

You'll want to add something like this to your ~/.config/fish/config.fish which is the equivalent of your ~/.bashrc

function tail_ls
  ls -l $1 | tail
end
innovati
  • 527
  • 1
  • 8
  • 12