
我剛剛遇到以下情況
grep -h ^ID= /etc/*-release
python -c 'from os import system; system("echo hello; echo $_")'
對於 RHEL,這給出了我的期望($_
擴展到hello
):
$ grep -h ^ID= /etc/*-release
ID="rhel"
$ python -c 'from os import system; system("echo hello; echo $_")'
hello
hello
但對於 Ubuntu (WSL) 則不然:
$ grep -h ^ID= /etc/*-release
ID=ubuntu
$ python -c 'from os import system; system("echo hello; echo $_")'
hello
/usr/bin/python
這是為什麼?
答案1
os.system
委託給 Csystem()
函數:
os.system(command)
在子 shell 中執行命令(字串)。這是透過呼叫標準C函數來實現的
system()
在 Linux 上定義為:
int system(const char *command);
此
system()
函式庫函數用於建立一個子進程,該子進程執行 使用fork(2)
中指定的shell命令,如下所示:command
execl(3)
execl("/bin/sh", "sh", "-c", command, (char *) NULL);
在 RHEL 上sh
是bash
,但在 Ubuntu 上是dash
。
$_
中未定義dash
,它是 bash 功能,因此存在差異。
在 Ubuntu/Debian 上,您可以使用設定 bash-as-shsudo dpkg-reconfigure dash
並在對話方塊中選擇「否」。