Alias with variable in bash

LinuxBash

Linux Problem Overview


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.

Linux Solutions


Solution 1 - Linux

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.

Solution 2 - Linux

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

Solution 3 - Linux

alias tail_ls='_tail_ls() { ls -l "$1" | tail ;}; _tail_ls'

Solution 4 - Linux

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

$ alias tail_ls='ls -l "$1" | tail'
$ set mydir
$ tail_ls

Solution 5 - Linux

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

Solution 6 - Linux

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeepank GuptaView Question on Stackoverflow
Solution 1 - LinuxMaxim SloykoView Answer on Stackoverflow
Solution 2 - LinuxjruzafaView Answer on Stackoverflow
Solution 3 - LinuxJavier LópezView Answer on Stackoverflow
Solution 4 - LinuxJ. ChomelView Answer on Stackoverflow
Solution 5 - Linuxl0b0View Answer on Stackoverflow
Solution 6 - LinuxinnovatiView Answer on Stackoverflow