如何以bash编程方式执行回车?

问题描述 投票:1回答:3

我的主文件是main.sh:

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

anotherscript.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中完成。

bash macos terminal iterm2 iterm
3个回答
0
投票

尝试

echo | source anotherscript.sh

0
投票

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

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

但是这仍然潜伏着一些危险:source命令在子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即可,无需任何管道。


0
投票

作为user1934428的注释,bash管道导致级联在子shell中执行的命令和变量修改没有反映在当前过程中。要更改此行为,您可以使用内置的lastpipe设置shopt。然后,bash更改作业控制,以使管道在当前shell中执行(就像tsch一样。)>

然后您可以尝试:

main_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.
© www.soinside.com 2019 - 2024. All rights reserved.