Using aliases with nohup

2019-04-06 08:43发布

问题:

Why doesn't the following work?

$ alias sayHello='/bin/echo "Hello world!"'
$ sayHello 
    Hello world!
$ nohup sayHello
    nohup: appending output to `nohup.out'
    nohup: cannot run command `sayHello': No such file or directory

(the reason I ask this question is because I've aliased my perl and python to different perl/python binaries which were optimized for my own purposes; however, nohup gives me troubles if I don't supply full path to my perl/python binaries)

回答1:

Because the shell doesn't pass aliases on to child processes (except when you use $() or ``).

$ alias sayHello='/bin/echo "Hello world!"'

Now an alias is known in this shell process, which is fine but only works in this one shell process.

$ sayHello 

Hello world!

Since you said "sayHello" in the same shell it worked.

$ nohup sayHello

Here, a program "nohup" is being started as a child process. Therefore, it will not receive the aliases. Then it starts the child process "sayHello" - which isn't found.

For your specific problem, it's best to make the new "perl" and "python" look like the normal ones as much as possible. I'd suggest to set the search path.

In your ~/.bash_profile add: export PATH="/my/shiny/interpreters/bin:${PATH}"

Then relogin.

Since this is an environment variable, it will be passed to all the child processes, be they shells or not - it should now work very often.



回答2:

For bash: Try doing nohup 'your_alias'. It works for me. I don't know why back quote is not shown. Put your alias within back quotes.



回答3:

With bash, you can invoke a subshell interactively using the -i option. This will source your .bashrc as well as enable the expand_aliases shell option. Granted, this will only work if your alias is defined in your .bashrc which is the convention.

Bash manpage:

If the -i option is present, the shell is interactive.

expand_aliases: If set, aliases are expanded as described above under ALIASES. This option is enabled by default for interactive shells.

When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist.


$ nohup bash -ci 'sayHello'


回答4:

If you look at the Aliases section of the Bash manual, it says

The first word of each simple command, if unquoted, is checked to see if it has an alias.

Unfortunately, it doesn't seem like bash has anything like zsh's global aliases, which are expanded in any position.