Alias with variable in bash
LinuxBashLinux 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:
-
In ~/.bashrc add:
sendpic () { scp "$@" mina@foo.bar.ca:/www/misc/Pictures/; }
-
Save the file and reload
$ source ~/.bashrc
-
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