Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing alias as function argument linux bash

Hi everyone I'm learning how to use the .bashrc file in linux and as my title states I'm wondering how to make a function recognize an argument as an alias

I have an alias called home defined as: alias home=$HOME

and a function go defined as

function go(){
cd $1
ls $1
}

but when I do go home i get

bash: cd: home: No such file or directory ls: cannot access home: No such file or directory

when I want it to do go $HOME

how would i go about implementing this?

like image 638
Alex Avatar asked Dec 15 '22 10:12

Alex


1 Answers

An alias is not a word substitution but a small newly created command:

$ alias bla=ls
$ bla
file1
file2
file3
…

So, it cannot be used in the way you assumed.

You might want to use variable substitution for this:

$ home=$HOME
$ function go() {
  cd "$(eval echo \$"$1")"
}
$ go home

In case you want to use an alias despite that this is an abuse, try this:

$ alias home=$HOME
$ function go() {
  cd "$(type "$1" | sed -e 's/.*is aliased to .//' -e 's/.$//')"
}
$ go home
like image 197
Alfe Avatar answered Jan 10 '23 11:01

Alfe