Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用sudobash-c';echo$myVariable';-bash脚本_Bash_Shell - Fatal编程技术网

使用sudobash-c';echo$myVariable';-bash脚本

使用sudobash-c';echo$myVariable';-bash脚本,bash,shell,Bash,Shell,我想在/etc/hosts文件中回显一个字符串。该字符串存储在名为$myString的变量中 运行以下代码时,回显为空: finalString="Hello\nWorld" sudo bash -c 'echo -e "$finalString"' 我做错了什么 您没有将变量导出到环境中,以便子流程可以拾取它 你还没有告诉sudo保护环境 \ 或者,您可以使用当前的shell替换: finalString="Hello\nWorld" sudo bash -c 'echo -e "'"$fi

我想在/etc/hosts文件中回显一个字符串。该字符串存储在名为
$myString
的变量中

运行以下代码时,回显为空:

finalString="Hello\nWorld"
sudo bash -c 'echo -e "$finalString"'
我做错了什么

  • 您没有将变量导出到环境中,以便子流程可以拾取它

  • 你还没有告诉sudo保护环境

  • \

    或者,您可以使用当前的shell替换:

    finalString="Hello\nWorld"
    sudo bash -c 'echo -e "'"$finalString"'"'
    
    您可以这样做:

    bash -c "echo -e '$finalString'"
    
    i、 e使用双引号将参数传递给子shell,因此变量(
    $finalString
    )按预期展开(由当前shell展开)

    尽管我建议不要将
    -e
    标志与
    echo
    一起使用。相反,您只需执行以下操作:

    finalString="Hello
    World"
    

    也就是说:使用
    export
    使变量在子shell中可用。要将变量导出到环境中,只是“export finalString”吗?因为它仍然没有打印变量。@user2771150在sudo-->
    sudo-ebash-c'echo-E“$finalString”
    中可能需要
    -E
    。它们都“安全”吗?有“推荐”的方法吗?很抱歉我对bash脚本非常陌生。
    finalString="Hello
    World"