Bash Shell 脚本/输入输出
外观
来自 help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
read 非常适合用户输入和读取标准输入/管道。
用户输入示例
# 'readline' prompt default variable name
read -e -p "Do this:" -i "destroy the ship" command
echo "$command"
甚至更简单
pause() { read -n 1 -p "Press any key to continue..."; }
Hello-world 级别的 stdout 操作示例
echo 'Hello, world!' | { read hello
echo $hello }
只要有创意。例如,在许多情况下,read 可以替换 whiptail。这是一个来自 Arthur200000 的 shell 脚本的示例
# USAGE
# yes_or_no "title" "text" height width ["yes text"] ["no text"]
# INPUTS
# $LINE = (y/n) - If we should use line-based input style(read)
# $_DEFAULT = (optional) - The default value for read
yes_or_no() {
if [ "$LINE" == "y" ]; then
echo -e "\e[1m$1\e[0m"
echo '$2' | fold -w $4 -s
while read -e -n 1 -i "$_DEFAULT" -p "Y for ${5:-Yes}, N for ${6:-No}[Y/N]" _yesno; do
case $_yesno in
[yY]|1)
return 0
;;
[nN]|0)
return 1
;;
*)
echo -e "\e[1;31mINVALID INPUT\x21\e[0m"
esac
else whiptail --title "${1:-Huh?}" --yesno "${2:-Are you sure?}" ${3:-10} ${4:-80}\
--yes-button "${5:-Yes}" --no-button "$6{:-No}"; return $?
fi
}
# USAGE
# user_input var_name ["title"] ["prompt"] [height] [width]
# INPUTS
# $LINE = (y/n) - If we should use line-based input style(read)
# $_DEFAULT = (optional) - The default value for read; defaults to nothing.
user_input(){
if [ "$LINE" == "y" ]; then
echo -e "\e[1m${2:-Please Enter:}\e[0m" | fold -w ${4:-80} -s
read -e -i "${_DEFAULT}" -p "${3:->}" $1
else
eval "$1"=$(whiptail --title "$2" --inputbox "$3" 3>&1 1>&2 2>&3)
fi
}
在 shell 中,重定向用于文件 I/O。最常见的用法是重定向标准流(stdin、stdout 和 stderr)以接受来自另一个程序通过管道输入,将程序输出保存为文件,以及通过将流重定向到 /dev/null
来抑制程序输出。