139

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
  • 337,988
  • 84
  • 391
  • 326
Deepank Gupta
  • 1,527
  • 3
  • 12
  • 11

6 Answers6

214

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,242
  • 2
  • 43
  • 50
Maxim Sloyko
  • 14,105
  • 9
  • 38
  • 47
35

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
  • 252,262
  • 96
  • 511
  • 570
jruzafa
  • 4,046
  • 1
  • 22
  • 25
34
alias tail_ls='_tail_ls() { ls -l "$1" | tail ;}; _tail_ls'
Javier López
  • 713
  • 8
  • 14
  • 3
    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
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
  • 7,889
  • 15
  • 41
  • 65
3

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

l0b0
  • 52,149
  • 24
  • 132
  • 195
  • 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
  • 519
  • 1
  • 7
  • 12