跳轉到內容

Bash Shell 指令碼/輸入輸出

來自 Wikibooks,開放書籍,開放世界

內建 read 命令

[編輯 | 編輯原始碼]

來自 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 重定向

[編輯 | 編輯原始碼]

在 shell 中,重定向用於檔案 I/O。最常見的用法是重定向標準流(stdin、stdout 和 stderr)以接受來自另一個程式透過管道輸入,將程式輸出儲存為檔案,以及透過將流重定向到 /dev/null 來抑制程式輸出。


華夏公益教科書