shell脚本echo在sudo中不起作用



我有一个shell脚本test.sh,如下所示。

sudo -H sh -c '
    echo $1;    
'

但是,当我以./test.sh abcd的身份运行这个脚本时,它并没有响应任何内容。然后我更改了我的脚本,如下所示。

sudo -H sh -c '
    echo $1;    
'

但现在,它将输出显示为$1。为了得到abcd的输出,我需要在这里做什么修改。请给我建议,因为我是一个非常初学者在shell脚本。

谢谢。

试试这个:

sudo -H sh -c "
  echo $1;    
"

sudo在一个新的shell中运行命令,该shell对传递给其父级的参数一无所知,因此在新的(子)shell中运行该命令字符串之前,需要展开这些参数。

尝试:

sudo -H sh -c '
echo "$1";    
' argv0 "$1"

来自bash手册页:

man bash | less -Ip '-c string'
# -c string If the -c option is present,  then  commands  are  read  from
# string.   If  there  are arguments after the string, they are
# assigned to the positional parameters, starting with $0.

最新更新