這是一個(gè)系列文章,主要分享shell(部分功能僅適用于bash)的使用建議和技巧,每次分享3點(diǎn),希望你能有所收獲。
1 重定向相關(guān)知識(shí)
- 重定向標(biāo)準(zhǔn)輸出到文件
$ echo line1 > test.log
$ cat test.log
line1
- 重定向標(biāo)準(zhǔn)錯(cuò)誤到文件
$ echo line1 2> error.log
line1
$ cat error.log
- 重定向標(biāo)準(zhǔn)輸出到標(biāo)準(zhǔn)錯(cuò)誤
$ echo line1 1>&2
line1
- 重定向標(biāo)準(zhǔn)錯(cuò)誤到標(biāo)準(zhǔn)輸出
$ echo line1 2>&1
line1
- 重定向標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤到文件
$ echo line1 > test.log 2>&1
$ cat test.log
line1
2 同時(shí)打印到屏幕和文件
$ cat tee_demo.sh
#!/bin/bash
echo_ext(){
echo "$1" 2>&1 | tee -a test.log
}
echo_ext line1
echo_ext line2
echo_ext line3
$ ./tee_demo.sh
line1
line2
line3
$ cat test.log
line1
line2
line3
在shell腳本中,如果需要同時(shí)將輸出信息打印到屏幕并保存到文件,可以通過tee命令實(shí)現(xiàn)。由示例中可以看到,定義了一個(gè)echo_ext函數(shù),封裝echo命令,將輸出信息打印到屏幕,并保存到test.log文件,tee命令的-a選項(xiàng)是將輸出信息append到文件,而不是覆蓋,運(yùn)行完tee_demo.sh腳本,查看test.log文件內(nèi)容,和屏幕輸出相同。
3 進(jìn)入上層目錄
$ pwd
/root/tmp
$ alias ..='cd .. && ls -l'
$ ..
total 20
-rw-------. 1 root root 2011 Feb 28 15:08 anaconda-ks.cfg
-rwxr-x---. 1 root root 8576 May 25 14:58 checkpoint_demo
drwxr-xr-x. 2 mpi_user1 mpi_user1 37 May 29 17:50 chkpnt_dir
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Desktop
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Documents
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Downloads
-rw-r--r--. 1 root root 2059 Feb 28 15:12 initial-setup-ks.cfg
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Music
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Pictures
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Public
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Templates
drwxr-xr-x. 2 root root 6 Jun 4 17:17 tmp
drwxr-xr-x. 2 root root 6 Feb 28 15:14 Videos
通過alias命令,定義一個(gè)新的..命令,當(dāng)執(zhí)行..命令時(shí),會(huì)自動(dòng)進(jìn)入上層目錄,然后列出上層目錄的所有文件,不需要執(zhí)行cd ..,然后執(zhí)行ls,更加方便快捷。所以,你還可以定義一個(gè)...命令,進(jìn)入上上層目錄。