> For the complete documentation index, see [llms.txt](https://kawsing.gitbook.io/opensystem/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kawsing.gitbook.io/opensystem/andoid-shou-ji/untitled-4/shell-script/hello-bash-printf.md).

# Hello,Bash:printf

printf 與echo 相同，會在終端機顯示輸出（stdout）

echo自動換行，但printf不會，須自帶\n換行

```bash
kawsing@ubuntu:~$ printf "hello"
hellokawsing@ubuntu:~$ printf "hello\n"
hello
kawsing@ubuntu:~$
```

printf可以格式化輸出字串，變數$HOME是環境變數，指的是個人家目錄

```bash
printf "我叫\"%s\"。\n很高興認識您。\n" "約翰"
printf "Your home folder is %s.\n" $HOME
```

```bash
printf '%(%Y%m%d %H:%M:%S)T\n'
```

printf-hello.sh

```bash
#!/bin/bash
printf "Hello %s   " "A先生" "B小姐" "C學生"
echo
```

```bash
#!/bin/bash
printf "Hello %s   \b\n" "A先生" "B小姐" "C學生"
```

### printf的轉義序列

| 序列    | 說明                                                                                      |
| ----- | --------------------------------------------------------------------------------------- |
| \a    | 警告字符，通常為ASCII的BEL字符                                                                     |
| \b    | 後退                                                                                      |
| \c    | 抑制（不顯示）輸出結果中任何結尾的換行字符（只在%b格式指示符控制下的參數字符串中有效），而且，任何留在參數里的字符、任何接下來的參數以及任何留在格式字符串中的字符，都被忽略 |
| \f    | 換頁（formfeed）                                                                            |
| \n    | 換行                                                                                      |
| \r    | enter（Carriage return）                                                                  |
| \t    | 水平製表符                                                                                   |
| \v    | 垂直製表符                                                                                   |
| \\\\  | 一個字面上的反斜杠字符                                                                             |
| \ddd  | 表示1到3位數八進制值的字符。僅在格式字符串中有效                                                               |
| \0ddd | 表示1到3位的八進制值字符                                                                           |

{% file src="/files/-LvdXwNrW9JseLRJvxd\_" %}
