【问题标题】:How do I programmatically execute a carriage return in bash?如何以编程方式在 bash 中执行回车?
【发布时间】:2020-05-14 17:38:41
【问题描述】:

我的主文件是 main.sh:

cd a_folder
echo "executing another script"
source anotherscript.sh
cd ..
#some other operations. 

另一个脚本.sh:

pause(){
   read -p "$*"
}
echo "enter a number: "
read number
#some operation
pause "Press enter to continue..."

我想跳过暂停命令。但是当我这样做时:

echo "/n" | source anotherscript.sh

它不允许输入数字。我希望出现“/n”,以便允许用户输入数字但跳过暂停语句。

PS:不能在 anotherscript.sh 中做任何更改。所有更改都在 main.sh 中完成。

【问题讨论】:

  • I wanted to skip the pause command 是什么意思?你能详细说明一下吗?暂停是用户定义的功能吗?你想通过修改main.sh来绕过
  • 没错,@Inian。相应地编辑了我的描述。
  • 要输出回车而不是echo "/n",您需要使用printf "\n",使用反斜杠而不是斜杠,或者最好只使用不带参数的echo
  • 考虑source anotherscript.sh < <(printf '\n' '1234' ''),它避免了需要causes the code to be sourceed in a completely different shell 的管道,从而破坏了首先使用source 的意义。

标签: bash macos terminal iterm2 iterm


【解决方案1】:

试试

echo | source anotherscript.sh

【讨论】:

  • 问题是 OP 希望他们采购的脚本在他们当前运行的 shell 的上下文中运行(要设置的变量等)。
【解决方案2】:

您的方法不起作用,因为要获取的脚本需要来自标准输入的 行:首先是包含数字的行,然后是空行(正在暂停)。因此,您必须向脚本提供两行,即数字和空行。如果您仍想从自己的标准输入中获取号码,则必须先使用read 命令:

echo "executing another script"
echo "enter a number: "
read number
printf "$number\n\n" | source anotherscript.sh

但这仍然潜伏着一些危险:源命令在子shell中执行;因此,anotherscript.sh 对环境所做的任何更改都不会在您的 shell 中可见。

一种解决方法是将读数逻辑放在 main.sh 之外:

# This is script supermain.sh
echo "executing another script"
echo "enter a number: "
read number
printf "$number\n\n"|bash main.sh

在 main.sh 中,您只需保留您的 source anotherscript.sh 而无需任何管道。

【讨论】:

    【解决方案3】:

    作为 user1934428 cmets,bash 管道导致级联 要在子 shell 中执行的命令和变量修改 没有体现在当前进程中。
    要更改此行为,您可以使用内置的 shopt 设置 lastpipe。 然后bash 更改作业控制,以便在 管道在当前 shell 中执行(就像tsch 所做的那样)。

    那请你试试:

    ma​​in_sh

    #!/bin/bash
    
    shopt -s lastpipe               # this changes the job control
    read -p "enter a number: " x    # ask for the number in main_sh instead
    cd a_folder
    echo "executing another script"
    echo "$x" | source anotherscript.sh > /dev/null
                                    # anotherscript.sh is executed in the current process
                                    # unnecessary messages are redirected to /dev/null
    cd ..
    echo "you entered $number"      # check the result
    #some other operations.
    

    这将正确打印number的值。

    你也可以这样说:

    #!/bin/bash
    
    read -p "enter a number: " x
    cd a_folder
    echo "executing another script"
    source anotherscript.sh <<< "$x" > /dev/null
    cd ..
    echo "you entered $number"
    #some other operations.
    

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 2020-02-11
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多