在交互式bash shell下运行系统命令 [英] Running system command under interactive bash shell

查看:393
本文介绍了在交互式bash shell下运行系统命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用system命令从Perl运行在我的~/.bashrc中别名的命令.它只能运行一次命令,效果很好,但是当我运行两次命令时,第二次调用将作为后台作业运行,然后挂起(与按<CTRL-Z>相同),并且我必须键入fg才能完成命令.例如

I am trying to run a command that has been aliased in my ~/.bashrc from Perl using the system command. It works well running the command only once, but when I run it twice the second invocation is run as a background job and then suspended (the same as pressing <CTRL-Z>) and I have to type fg to complete the command. For example

use strict;
use warnings;

system ('bash -ic "my_cmd"');
system ('bash -ic "my_cmd"');

第二个呼叫永远不会结束.输出为[1]+ Stopped a.pl.

The second call never completes. The output is [1]+ Stopped a.pl.

注意:

  • 用其他任何命令(例如ls)替换my_cmd时,也会获得相同的结果.
  • 似乎与我的~/.bashrc文件的内容无关.我试图从中删除所有内容,但问题仍然存在.
  • The same result is obtained when replacing my_cmd with any other command, for example ls.
  • It seems not to depend of the contents of my ~/.bashrc file. I tried to remove everything from it, and the problem still persisted.

我正在使用Ubuntu 14.04和Perl 5.18.2版.

I am using Ubuntu 14.04 and Perl version 5.18.2.

更新

为了调试,我将~/.bashrc减小为

echo "Entering ~/.bashrc .."
alias my_cmd="ls"
alias

和我的~/.bash_profile

if [ -f ~/.bashrc ]; then
    echo "Entering ~/.bash_profile .."
    . ~/.bashrc
fi

正在运行:

system ('bash -lc "my_cmd"');
system ('bash -lc "my_cmd"');

给予

Entering ~/.bash_profile ..
Entering ~/.bashrc ..
alias my_cmd='ls'
bash: my_cmd: command not found
Entering ~/.bash_profile ..
Entering ~/.bashrc ..
alias my_cmd='ls'
bash: my_cmd: command not found

并运行

system ('bash -ic "my_cmd"');
system ('bash -ic "my_cmd"');

给予

Entering ~/.bashrc ..
alias my_cmd='ls'
a.pl  p.sh

[1]+  Stopped                 a.pl

推荐答案

我认为您应该使用-l(或--login)开关,而不是对交互式外壳使用-i开关就像被当作登录外壳调用一样.

Rather than using the -i switch for an interactive shell, I think you should use the -l (or --login) switch, which causes bash to act as if it had been invoked as a login shell.

默认情况下,使用-l开关不会加载~/.bashrc.根据man bash,在登录外壳中,将加载/etc/profile/,然后是从~/.bash_profile/~/.bash_login~/.profile/找到的第一个文件.在我的系统上,我在~/.bash_profile中具有以下内容,因此已加载~/.bashrc:

Using the -l switch doesn't load ~/.bashrc by default. According to man bash, in a login shell, /etc/profile/ is loaded, followed by the first file found from ~/.bash_profile/, ~/.bash_login or ~/.profile/. On my system, I have the following in ~/.bash_profile, so ~/.bashrc is loaded:

# Source .bashrc
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

现在正在加载您的~/.bashrc,您需要启用别名扩展,该扩展在非交互式shell中是关闭的.为此,您可以在设置别名之前添加以下行:

Now that your ~/.bashrc is being loaded, you need to enable the expansion of aliases, which is off in a non-interactive shell. To do this, you can add the following line before setting your aliases:

shopt -s expand_aliases

这篇关于在交互式bash shell下运行系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆