Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a Bash alias over ssh

Tags:

bash

ssh

Here's what I'm trying to do:

ssh andy@<ip_address> "cat .bash_aliases; sayhello"

Here's what happens:

alias sayhello="echo hello"
bash: sayhello: command not found

To be more specific about my problem I'm trying to invoke the command
"sudo etherwake -i eth0 <mac_address>" over ssh -- this executes (I think) on my local computer, giving a sudo: unable to resolve host [blabla] error. It seems like any commands that are not standard bash commands are parsed by my local machine.

If that's what's happening, how do I get around it? If not, what is the explanation?

like image 686
mathandy Avatar asked Jun 15 '17 02:06

mathandy


1 Answers

In general this is not a good idea to use aliases in scripts.

Yet I can suggest one way to do it, but bare in mind how unsafe it is.

  • It relies on eval,
  • It reads remote files into the shell context.

Here we go.

ssh remote_host "shopt -s expand_aliases ; source ~/.bash_aliases ; eval sayhello"

Explanation:

  1. By default alias expansion is enabled only for interactive shells. To turn it on use shopt -s command.

  2. You will need to source the aliases into your shell context anyway.

  3. Now you are set to use your aliases via the eval command.

like image 50
Dmitri Chubarov Avatar answered Oct 12 '22 22:10

Dmitri Chubarov